NoName
NoName

Reputation: 10324

CSS DOM Traversal superior than JavaScript DOM Traversal?

JavaScript and CSS both use its own DOM tree when traversing through HTML elements.

In JavaScript, we can use its own DOM traversal methods such as

element.parentNode
element.nextSibling

However, this way is very unintuitive because JavaScript's DOM Tree contains things other than the HTML elements which can be easy to mess up for a developer.

i.e.

<div>
     <p>
     </p>
</div>

JavaScript's DOM Tree has <div> as the parent and 3 children:

text node: \n\t

element node: <p>

text node: \n

This becomes increasingly more difficult to keep track as the HTML document structure increases in complexity because not all HTML elements have a newline before and after among other things.

Thankfully, JavaScript allows us to use CSS's DOM traversal using:

element.querySelector("CSSselectorHere")

Since CSS's DOM Tree only contains the HTML elements, that makes it much easier to implement.

The case only I could think of where JavaScript's DOM Tree would be advantageous is if you are trying to color the text "cdf" red in the following:

In HTML:

<p> abc <a href="...">link</a> cdf </p>

In JavaScript:

pElementVariable.firstChild.nextSibling.nextSibling.classList.add("CSSclassRed");

However, wouldn't a better HTML practice be to just enclose the unique text like so?

<p> abc <a href="...">link</a> <span>cdf</span> </p>

Thus, styling the span using CSS's DOM traversal is possible. (assuming we're using traversal methods only, no ids)

If so, does .querySelector, an enabler in JavaScript for CSS's DOM traversal, make JavaScript's own built-in DOM traversal methods obsolete?

Upvotes: 2

Views: 1284

Answers (1)

Oriol
Oriol

Reputation: 288080

No. CSS is more limited, because it can only select elements (and pseudo-elements, but not through querySelector, but that might change).

Using the DOM you can traverse arbitrary nodes in the tree. That's more powerful. And if you want to restrict to elements, you can:

node.childNodes; // All child nodes
parentNode.children; // Only element child nodes

node.firstChild; // First node child
parentNode.firstElementChild; // First element child

node.lastChild; // Last node child
parentNode.lastElementChild; // Last element child

node.previousSibling; // The previous sibling node
nonDoctypeChildNode.previousElementSibling; // The previous sibling element

node.nextSibling; // The next sibling node
nonDoctypeChildNode.nextElementSibling; // The next sibling element

node.parentNode; // The parent node
node.parentElement; // The parent node, only if it's an element

So you don't need CSS APIs for things like that. And in particular you shouldn't modify your HTML to be able to use CSS APIs.

Upvotes: 6

Related Questions