Inconsistent Whitespace Text Nodes in Internet Explorer

前端 未结 5 1639
一生所求
一生所求 2020-12-09 22:03

The following source code alerts the following results:

Internet Explorer 7: 29
Firefox 3.0.3: 37 (correct)
Safari

5条回答
  •  佛祖请我去吃肉
    2020-12-09 22:25

    IE tries to be helpful and hides text nodes that contain only whitespace.

    In the following:

    W3C DOM spec says that

    has 3 child nodes ("\n", and "\n"), IE will pretend there's only one.

    The solution is to skip text nodes in all browsers:

    var node = element.firstChild;
    while(node && node.nodeType == 3) node = node.nextSibling;
    

    Popular JS frameworks have functions for such things.

提交回复
热议问题