If innerHTML is evil, then what's a better way change the text of a link?

橙三吉。 提交于 2019-11-30 08:41:23

How about

document.getElementById('mylink').firstChild.nodeValue = new_text;

This won't suffer from the problems described by PEZ.

Regarding Triptych's comment and bobince's reply, here's another solution:

var oldLink = document.getElementById('mylink'),
    newLink = oldLink.cloneNode(false);
newLink.appendChild(document.createTextNode(new_text));
oldLink.parentNode.replaceChild(newLink, oldLink);

innerHTML is not evil at all. There's nothing wrong with using it, as long as you're aware of the consequences.

For browsers supporting DOM3 you can use textContent:

document.getElementById("mylink").textContent = new_text;

This works in FF(tested in 3), Opera (tested in 9.6) and Chrome (tested in 1) but not in MSIE7 (haven't tested in MSIE8)

Added example

It's not pretty but should work cross browser (tested in win in FF3, Opera9.6, Crome1 and MSIE7)

function replaceTextContent(element,text) {
    if (typeof element ==="string") element = document.getElementById(element);
    if (!element||element.nodeType!==1) return;
    if ("textContent" in element) {
        element.textContent = text; //Standard, DOM3

    } else if ("innerText" in element) {
        element.innerText = text; //Proprietary, Micosoft
    } else {
        //Older standard, even supported by Microsoft
        while (element.childNodes.length) element.removeChild(element.lastChild);
        element.appendChild(document.createTextNode(text));
    }
}

(updated: added support for Microsofts proprietary innerText)

innerHTML has side effects (like disconnecting existing DOM nodes and rerendering that might be heavy). One needs to be aware of these effects. And anyone maintaining the code will need to be alert to that innerHTML is used or they might run into strange bugs.

Up until a year ago, innerHTML was just a lot faster than manipulating events via the DOM. I haven't checked the latest versions of all major browsers for this myself.

Firefox for example doesn't handle this well. It sometimes only updates the screen to reflect the change. If you query the DOM after the change, it still has the old values.

Example: try to change the value of a textarea via innerHTML, and then post the form. It'll silently post the value that the textarea had before. Think of the catastrophic results that something like that could have.

Maybe it's just some standard addicts who reject the idea of innerHTML.

innerHTML is the practical standard because all browsers implement it though it's not a W3C standard.

Just use it. It works like a charm.

Another option is to have two divs and use .hide() & .show().

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