Alternative for innerHTML?

江枫思渺然 提交于 2019-12-17 15:23:46

问题


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.


回答1:


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>");



回答2:


The better way of doing it is to use document.createTextNode. One of the main reasons for using this function instead of innerHTML is that all HTML character escaping will be taken care of for you whereas you would have to escape your string yourself if you were simply setting innerHTML.




回答3:


You can get the same effect by manipulating the DOM. The safest way to change text is to remove all the child nodes of the element and replace them with a new text node.

var node = document.getElementById("one");

while( node.firstChild )
    node.removeChild( node.firstChild );
node.appendChild( document.createTextNode("Two") );

Removing the child nodes gets rid of the text content of your element before replacing it with the new text.

The reason most developers avoid using innerHTML is that accessing elements through the DOM is standards compliant.




回答4:


If you only want to change plain text, then there's a quicker solution that relies on standards:

document.getElementById("one").firstChild.data = "two";

Anyway, please note that innerHTML is going to be part of the upcoming HTML 5 standard.




回答5:


Simple.

Replace text.innerHTML = 'two' with text.firstChild.nodeValue = 'two'.




回答6:


var who=document.getElementById('one'), txt='new text';
if(who.innerText) who.innerText=txt;
else if(who.textContent) who.textContent= txt;

This may be as objectionable as innerHTML to you, but it has the advantage of working in some cases (IE) where innerHTML or appendChild do not, like some table nodes, the text of style and script elements and the value of form fields




回答7:


Also looking for a good alternative to bypass element.innerHTML I finally found that solution:

HTMLElement.prototype.htmlContent = function(html)
{
    var dom = new DOMParser().parseFromString('<template>'+html+'</template>', 'text/html').head;
    this.appendChild(dom.firstElementChild.content);
}

//-- document.getElementById('my-id').innerHTML = string_of_html;
document.getElementById('my-id').htmlContent(string_of_html);

Another alternative without <template> tags, but loop instead:

HTMLElement.prototype.htmlContent = function(html)
{
    var dom = new DOMParser().parseFromString(html, 'text/html').body;
    while (dom.hasChildNodes()) this.appendChild(dom.firstChild);
}

Keep in mind that this method actually 'add' content when innerHTML 'replace' content...

This may help:

HTMLElement.prototype.clearContent = function()
{
    while (this.hasChildNodes()) this.removeChild(this.lastChild);
}

//-- document.getElementById('my-id').innerHTML = '';
document.getElementById('my-id').clearContent();

doc: https://github.com/swannty/escaping-innerHTML
perf: https://jsperf.com/escaping-innerhtml




回答8:


You could use DOM as follows:

<html>
<body>
<div>before</div>
<script type="text/javascript">
var element = document.getElementsByTagName("div")[0];
alert(element.firstChild.nodeValue);
element.removeChild(element.firstChild);
element.appendChild(document.createTextNode('after'));
alert(element.firstChild.nodeValue);
</script>
</body>

But I think anyone rarely do this but use a framework like jQuery or Prototype or any other javascript framework out there instead. This is jquery example:

<html>
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.2.6/jquery.min.js"></script>
</head>
<body>
<div>before</div>
<script type="text/javascript">
var element = $("div");
alert(element.text());
element.text("after");
alert(element.text());
</script>
</body>



回答9:


It appears to me that the CSS+HTML+JS combination should achieve desired effects:

.myelement:before {   
    content: attr(alt);
} 

...

<span class='myelement' alt='initial value'></span> 

...

element.setAttribute('alt', 'new value'); 

Does anyone know if this works in practice?




回答10:


Well i f i understand your question properly this should be an answer.

var text = document.getElementById("one");
//text.innerHTML = "Two";
 text.childNodes[0].nodeValue="two";



回答11:


insertAdjacentHTML() is the way to go. Read more: Click for documentation




回答12:


I sometimes find it helpful to store a direct reference to the text node if I am going to be updating it regularly. I do something like this:

var dynamicText = myDiv.appendChild(document.createTextNode("the initial text"));

And then whenever I need to update it, I just do this:

dynamicText.nodeValue = "the updated text";

This prevents having to walk the DOM or add or remove any children.



来源:https://stackoverflow.com/questions/718091/alternative-for-innerhtml

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!