Targeting Elements
In the CSS chapter, you learned about how to target your elements with ids and classes:
You can do pretty much the same with JavaScript, with some differences in the syntax. Don't worry, we won't go into too much detail on how JS works at this point.
To target an element using JS, you start with the outermost node of the tree - the document.
Then you can work you way down to reach the desired node using one of several methods.
To get all of the elements with based on their class:
To get an element based on its id:
To get an element based on its html tag:
(P.S.: Don't forget your '' and (), which are very important in JS, as you'll learn in the upcoming weeks.)
You can - and should - also use a more general method - querySelector:
And since we're talking about a tree-based system, you can navigate between nodes based on the relationships between elements. Let's say you have an html structure that resembles:
A way of accessing the image while navigating through the surrounding nodes:
Can you make sense of what we're doing here?
We'll look into the document node, find the element with the class of "page-title", then move onto the next sibling, which is the figure element, and then grab its first and only child, the image. It might seem a bit like an overkill in this example, but when working with a full-on DOM structure, it might be the simpler way.
We could then change the image from a cat, to a dog, as long as it exists in the repository:
Note: You can also retrieve the element that comes before using .previousSibling, or its parent with .parentNode. If an element has a couple of children elements, then you can access them using .childNodes[number], where number represents the child's position, starting by 0.