简体   繁体   中英

document.getElementById not working in Mozilla

I am having an issue with document.getElementByID in Mozilla. In the IE and Chrome my code is working well.

I have written the following code:

<script type="text/javascript">
function test(x, y) {
var text1 = document.getElementById('text1');
 for (var i = 0; i < x.length; i++) {
    text1.innerText += x[i]; // prints 12345
  }
   text1.innerText += "\ny: " + y; // prints y: 1,2,3,4,5
  }
</script>


 <body>
<form id="form1" runat="server">
<div>
    <asp:Button ID="Button1" runat="server" OnClick="Button1_Click" Text="Button" />
</div>
<div id="text1"></div>
</form>
</body>

Can any one tell why this doesn't work in FireFox?

I don't think it's the call to getElementById that's the problem — if it is, then you didn't give enough detail — but I can tell you that Firefox and some other browsers do not implement innerText . For those browsers, you need to work with textContent or text nodes directly.

You can find out whether textContent is supported or not using feature detection:

var textContentOrInnerText = "textContent" in document.body 
                               ? "textContent" : "innerText";

Then, you use this variable for the property access in your code:

text1[textContentOrInnerText] += x[i];

Feel free to shorten the variable to something you feel more comfortable with. Note that there are some minor differences in behaviour between both properties, but mostly you won't notice them.

textContent is the standards behaviour which is why I test for that first in my code.

innerText is not referenced anywhere in the DOM standard, therefore it's non-standard and an IE only hack.

Please use .textContent to get the text content.

For browser support either use a library or a shim

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM