When selecting elements from the DOM, we can either select one or many nodes. Let's start with retrieving a single element.
To retrieve an element, we use DOM queries. These are the methods used through JavaScript that we can use to find elements on the DOM tree. Oftentimes, the elements we select are stored into a variable, which serves as a reference to the node; this is known as caching.
The most efficient way to obtain an element is through its id
attribute. We may do this with the getElementById()
method, in which we simply pass in the name of the id
. Since we know that no two elements can share the same id
, we are ensured that the browser terminates right after finding the first id
, resulting in quickness and responsivity.
var firstItem = document.getElementById('first')
This command will store the reference to the element with an id
of first
within the firstItem
variable.
Another way to select just one element is through a query selector. Given a CSS selector, this returns only the first matched item.
firstParagraph = document.querySelector('p') # First tag.
document.querySelector('.item') # First element with a class "item"
Once we have selected a single element, we may access the nodes around it through these properties:
parent
previousSibling
nextSibling
firstChild
lastChild
This foam seat cushion relieves lowerback pain, numbness and pressure sores by promoting healthy weight distribution, posture and spine alignment. Furthermore, it reduces pressure on the tailbone and hip bones while sitting. Perfect for sitting on the computer desk for long periods of time.
$ Check priceThis book was written for anyone who wants to use JavaScript to make their websites a little more interesting, engaging, interactive, or usable. In particular, it is aimed at people who do not have a degree in computer science (well, not yet anyway).
$ Check priceAd