Ariyan
Ariyan

Reputation: 15138

forcing firefox skip "text nodes" in DOM parsing by javascript

Hi
I'm writing a javascript code to traverse HTML dom and highlight elements.
My problem is firefox returns whitespaces as text node.
Is there any solution to force it to just return tags? for example I need "firstChild" always return first tag and not any text!

Thanks

Upvotes: 0

Views: 1288

Answers (3)

Neil
Neil

Reputation: 55402

Maybe you could try one of the other DOM traversal methods, such as a TreeWalker.

Upvotes: 1

gblazex
gblazex

Reputation: 50109

You can check if a node is an element with node.nodeType === 1.

You can also implement the new DOM Travelsal API as functions.

var dummy = document.createElement("div");
var firstElementChild = ('firstElementChild' in dummy)
    ? function (el) {
      return el.firstElementChild;
    }
    : function (el) {
        el = el.firstChild;
        while (el && el.nodeType !== 1)
            el = el.nextSibling;
        return el;
    }

usage

firstElementChild(el)

Upvotes: 3

Yi Jiang
Yi Jiang

Reputation: 50115

You can use element.firstElementChild instead. Unfortunately, this isn't supported in IE8 and below.

Alternatively, you might want to write a small function to crawl the childNodes until you find the next element node.

Upvotes: 3

Related Questions