Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
141 views
in Technique[技术] by (71.8m points)

javascript - Alternative for innerHTML?

EDIT: WOW. This question is 12 years old now.

As someone stated, it can be done with a one-liner since 2016: https://stackoverflow.com/a/69322509/80907


The original:

I'm wondering if there's a way to change the text of anything in HTML without using innerHTML.

Reason I'm asking is because it's kinda frowned upon by the W3C. I know it's nitpicking, but I just wanna know, is there a way?

EDIT: people seem to misunderstand what I'm asking here: I want to find a way to effectivly change the text being displayed.

If I have:

<div id="one">One</a>

innerHTML allows me to do this:

var text = document.getElementsById("one");
text.innerHTML = "Two";

And the text on my screen will have changed.
I do not wish to append more text, I wish to change allready existing text.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

The recommended way is through DOM manipulation, but it can be quite verbose. For example:

// <p>Hello, <b>World</b>!</p>
var para = document.createElement('p');
para.appendChild(document.createTextNode('Hello, '));

// <b>
var b = document.createElement('b');
b.appendChild(document.createTextNode('World');
para.appendChild(b);

para.appendChild(document.createTextNode('!'));

// Do something with the para element, add it to the document, etc.

EDIT

In response to your edit, in order to replace the current content, you simply remove the existing content, then use the code above to fill in new content. For example:

var someDiv = document.getElementById('someID');
var children = someDiv.childNodes;
for(var i = 0; i < children.length; i++)
    someDiv.removeChild(children[i]);

But as someone else said, I'd recommend using something like jQuery instead, as not all browsers fully support DOM, and those that do have quirks which are dealt with internally by JavaScript libraries. For example, jQuery looks something like this:

$('#someID').html("<p>Hello, <b>World</b>!</p>");

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...