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

前端 未结 1 1272
悲&欢浪女
悲&欢浪女 2021-01-25 14:25

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

相关标签:
1条回答
  • 2021-01-25 15:03

    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.

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