JS DOM - 01.04 - Selectors

‘document.getElementById’

If an element has the id attribute, we can get the element using the method document.getElementById(id), no matter where it is.

<script>
	let elem = document.getElementById('elem');

	elem.style.background = "red";
</script>

The method getElementById can be called on document object. It looks for the given id in the whole document.

‘querySelectorAll’

By far, the most versatile method, elem.querySelectorAll(css) returns all elements inside elem matching the given CSS selector.

element.querySelectorAll(selectors) 
// returns 'NodeList' containing references to all matches of the 'selector'

NodeList is not an Array even though it looks like an array it has several array methods missing from it.
It can be converted to an Array using Array.from() or spread operator

<ul>
	<li>The</li>
	<li>test</li>
</ul>

<ul>
	<li>has</li>
	<li>passed</li>
</ul>
let elements = document.querySelectorAll('ul > li:last-child');

for (let elem of elements) {
	alert(elem.innerHTML);    // test, passed
		}

Pseudo-classes in the CSS selector like :hover and :active are also supported.

document.querySelectorAll(':hover') will return the collection with elements that the pointer is over now (in nesting order: from the outermost <html> to the most nested one).

querySelector(selector)

elem.querySelector(css selector) returns the first element for the given CSS selector.

element.querySelector(selector) 
// returns a reference to the first match of 'selector'

The result is the same as elem.querySelectorAll(css)[0], but the latter is looking for all elements and picking one, while elem.querySelector just looks for one. So it’s faster and also shorter to write.


elem.matches

The elem.matches(css) does not look for anything, it merely checks if elem matches the given CSS-selector. It returns true or false.


elements / tags

“element” nodes are primarily used for manipulating the DOM

<div id = "container">
	<div class = "display"> </div>
	<div class = "controls"> </div>	
</div>

Here there is a parent and its children which are on the next level, each on their own branch.

Targeting nodes with selectors

When working with DOM, ‘selectors’ are used to target the nodes to be worked on.
Using CSS style selectors to target the <div class = "display"> </div>:

/* CSS selectors */
.display
div.display
#container > .display
div#container > div.display

Using relational selectors (i.e firstElementChild or lastElementChild) with special properties owned by the nodes.
Identifying a certain node based on its relationship to the nodes around it.

// selects the #container div
const container = document.querySelector("#container");

// selects the first child of #container  i.e .display
console.dir(container.firstElementChild);

// selects the .controls div
const controls = document.querrySelector(".controls");

// selects the prior sibling of control i.e .display
console.dir(controls.previousElementSibling);