📜 ⬆️ ⬇️

Empty text nodes in Internet Explorer

I think the post will be interesting for beginners to learn JavaScript and DOM.

Recently, I spent more than half an hour trying to understand why the code below returns "undefined" in all browsers except Internet Explorer.

< html > <br><br> < head > <br> < title ></ title > <br> </ head > <br><br> < body > <br><br> < div > <br> < h1 > Header </ h1 > <br> < p > Paragraph </ p > <br> </ div > <br><br> < script type ="text/javascript" > <br> alert( document .getElementsByTagName( 'div' )[0].firstChild.tagName);<br> </ script > <br><br> </ body > <br><br> </ html > <br><br> * This source code was highlighted with Source Code Highlighter .


It may seem to a beginner to learn JavaScript that the above script should output the string "H1", since It is logical to assume that the H1 element is the first child node ( node 'om) of the DIV element. But it is not. If you follow the Document Object Model Core specification, line breaks, spaces, and other non-print characters are text nodes. Thus, in the above code, the string document.getElementsByTagName('div')[0].firstChild returns a text node that does not have the tagName property (since, in fact, it is not a tag).
')
In the code below, the DIV element will have not two child nodes, as it may first appear, but five.

< div > <br> < h1 > Header </ h1 > <br> < p > Paragraph </ p > <br> </ div >


These nodes are: " \n ", " H1 ", " \n ", " P ", " \n ". Three of them are text nodes , two are element nodes .

This will be the case for all standards-compliant browsers. But Internet Explorer purposely misses empty text nodes, i.e. nodes containing only non-printable characters. Therefore, in InternetExplorer, the DIV node will contain not five, but two child nodes.

On the QuirksMode.org test page, you can experiment with the childNodes property and make sure that IE does not count empty text nodes.

Source: https://habr.com/ru/post/72773/


All Articles