childNodes[] not working in IE9 as in IE7 and 8

2020-04-19 08:38发布

问题:

I have some code that works in IE7 and 8 but not in 9

var table = document.getElementById('RadGrid_ctl01').childNodes[2];

which doesn't work in IE9, now I did read that IE9 count white spaces etc and therefore the index won't be the same as in IE7 and IE8 so I debugged and found same values when I changed index from 2 to 4 like so:

var table = document.getElementById('RadGrid_ctl01').childNodes[4];

However when I later on try to access the table object with this code

var editor = table.childNodes[i].childNodes[j].childeNodes[0]

the variable editor will get the expected value in IE7 and IE8, but in IE9 it becomes null since the childNodes[j] doesn't have any children. I have no idea what causes this. both i and j starts at 0.

Anyone know what I am doing wrong?

回答1:

The behaviour of IE9 is right, lower versions are wrong. The problem is caused by whitespace between two html-tags, which should lead into text-nodes.

UPDATE: Added example

<ul><li>Foo</li><li>Bar</li></ul>

<ul>
    <li>Foo</li>
    <li>Bar</li>
</ul>

Looks pretty much the same, doesn't it? However the resulting DOM differs. First example would result in:

- ul
-- li
--- (text)Foo
-- li
---(text)Bar

While the second Markup leads into this:

- ul
-- (text)
-- li
--- (text)Foo
-- (text)
-- li
--- (text)Bar
-- (text)

And since text-nodes cannot have any child-nodes, this causes your Javascript to fail silently.

Possible solution

One solution is to strip out the empty text-nodes. I once wrote a gist for this issue.

UPDATE:

Node.normalize() seems to be a more reliable solution, but i didn't check it for browser-compatibilty.