Why does IE give unexpected errors when setting innerHTML

后端 未结 10 2739
面向向阳花
面向向阳花 2020-12-10 17:20

I tried to set innerHTML on an element in firefox and it worked fine, tried it in IE and got unexpected errors with no obvious reason why.

For example if you try and

相关标签:
10条回答
  • 2020-12-10 17:58

    http://www.ericvasilik.com/2006/07/code-karma.html

    0 讨论(0)
  • 2020-12-10 17:59

    You're seeing that behaviour because innerHTML is read-only for table elements in IE. From MSDN's innerHTML Property documentation:

    The property is read/write for all objects except the following, for which it is read-only: COL, COLGROUP, FRAMESET, HEAD, HTML, STYLE, TABLE, TBODY, TFOOT, THEAD, TITLE, TR.

    0 讨论(0)
  • 2020-12-10 18:00

    Have you tried setting innerText and/or textContent? Some nodes (like SCRIPT tags) won't behave as expected when you try to change their innerHTML in IE. More here about innerText versus textContent:

    http://blog.coderlab.us/2006/04/18/the-textcontent-and-innertext-properties/

    0 讨论(0)
  • 2020-12-10 18:00

    Are you setting a completely different innerHTML or replacing a pattern in the innerHTML? I ask because if you're trying to do a trivial search/replace via the 'power' of innerHTML, you will find some types of element not playing in IE.

    This can be cautiously remedied by surrounding your attempt in a try/catch and bubbling up the DOM via parentNode until you successfully manage to do it.

    But this is not going to be suitable if you're inserting brand-new content.

    0 讨论(0)
  • 2020-12-10 18:01

    I just figured out that if you try to set innerHTML on an element in IE that isn't logically correct it will throw this error. For example if you try and set the innerHTML of a table to " hi from stu " it will fail, because the table must be followed by a sequence. Apparently firefox isn't this picky. Hope it helps.

    0 讨论(0)
  • 2020-12-10 18:02

    check the scope of the element you are trying to set the innerHTML. since FF and IE handle this in a different way

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