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?
abc
linkcdf
In CSS: p{display:inline}; – NoName Oct 18 '16 at 04:32