'innerText' works in IE, but not in Firefox

前端 未结 15 1286
执念已碎
执念已碎 2020-11-21 05:01

I have some JavaScript code that works in IE containing the following:

myElement.innerText = \"foo\";

However, it seems that the \'innerTex

相关标签:
15条回答
  • 2020-11-21 05:26
    myElement.innerText = myElement.textContent = "foo";
    

    Edit (thanks to Mark Amery for the comment below): Only do it this way if you know beyond a reasonable doubt that no code will be relying on checking the existence of these properties, like (for example) jQuery does. But if you are using jQuery, you would probably just use the "text" function and do $('#myElement').text('foo') as some other answers show.

    0 讨论(0)
  • 2020-11-21 05:29

    A really simple line of Javascript can get the "non-taggy" text in all main browsers...

    var myElement = document.getElementById('anyElementId');
    var myText = (myElement.innerText || myElement.textContent);
    
    0 讨论(0)
  • 2020-11-21 05:30

    As per Prakash K's answer Firefox does not support the innerText property. So you can simply test whether the user agent supports this property and proceed accordingly as below:

    function changeText(elem, changeVal) {
        if (typeof elem.textContent !== "undefined") {
            elem.textContent = changeVal;
        } else {
            elem.innerText = changeVal;
        }
    }
    
    0 讨论(0)
  • 2020-11-21 05:33

    If you only need to set text content and not retrieve, here's a trivial DOM version you can use on any browser; it doesn't require either the IE innerText extension or the DOM Level 3 Core textContent property.

    function setTextContent(element, text) {
        while (element.firstChild!==null)
            element.removeChild(element.firstChild); // remove all existing content
        element.appendChild(document.createTextNode(text));
    }
    
    0 讨论(0)
  • 2020-11-21 05:34

    jQuery provides a .text() method that can be used in any browser. For example:

    $('#myElement').text("Foo");
    
    0 讨论(0)
  • 2020-11-21 05:36

    innerText has been added to Firefox and should be available in the FF45 release: https://bugzilla.mozilla.org/show_bug.cgi?id=264412

    A draft spec has been written and is expected to be incorporated into the HTML living standard in the future: http://rocallahan.github.io/innerText-spec/, https://github.com/whatwg/html/issues/465

    Note that currently the Firefox, Chrome and IE implementations are all incompatible. Going forward, we can probably expect Firefox, Chrome and Edge to converge while old IE remains incompatible.

    See also: https://github.com/whatwg/compat/issues/5

    0 讨论(0)
提交回复
热议问题