0

I've read the following very good article: Difference between Node object and Element object? as to clear out the difference between a node object and an element object. I 've understood that

element objects are a subset of node objects.

So, after that I've come upon the following query: In which way may I iterate through all the node objects? By using document.getElementsByTagName('*') ,I think I am getting all the element objects since all of them have value 1 for their .nodeType property. Am I right and if yes, how may I include into my results all these nodes that are not elements?

Thank you

Community
  • 1
  • 1
Unknown developer
  • 5,414
  • 13
  • 52
  • 100

2 Answers2

1

I don't believe there's any standard DOM function that will return every Node (as opposed to Element) in the entire document.

You would probably have to use recursive DOM traversal to find them all with something like this:

function getAllNodes(parent, nodes) {
    parent = parent || document;
    nodes = nodes || [];

    var child = parent.firstChild;
    while (child) {
        nodes.push(child);
        if (child.hasChildNodes) {
            getAllNodes(child, nodes);
        }
        child = child.nextSibling;
    }
    return nodes;
}

As written you can just write var nodes = getAllNodes() and it'll automatically start at the document root.

Alnitak
  • 334,560
  • 70
  • 407
  • 495
1

The answer is in your question. You use document.getElementsByTagName. Let me repeat that for you. getElementsByTagName.

Non-element nodes don't have a tag name, an identifier, or anything like that. The only way to designate them is by where they are in the document structure.

You can get a reference to an Element and then browse its childNodes, as has been suggested already.

Another way is to use an XPath, which, unlike CSS selectors, is able to point directly to any Node, including text and comment Nodes.

document.evaluate("*", document.documentElement, null, XPathResult. UNORDERED_NODE_ITERATOR_TYPE)
Touffy
  • 6,309
  • 22
  • 28