Accessing DOM
Now that we understand what DOM is and the fundamentals of HTML and CSS, it’s time to learn how to access this object template. Let’s take a look at some fundamental concepts!
Simple Selection with getElementById
To begin, we can select a specific element using the getElementById method. This is useful when you want to pick up an item with a specific ID. Look at it.
var myTitel = document.getElementById('myTitel');
Here, we assume that we have an item with the “myTitle” ID. Easy, right?
Selection by Tag with getElementsByTag
Sometimes we want to select multiple items with the same tag. The getElementsByTagName method is the hero here:
var paragraphs = document.getElementsByTag
Now, all paragraphs are in the hands of our variable paragraph.
Selection by Class with getElementsByClass
If we want to pick up elements by their class, we use getElementsByClassName:
var elementsAzuis = document.getElementsByClass
Here, we’re assuming that all blue elements have the “blue” class.
Advanced Selection with querySelector and quarySelectorAll
For a more accurate selection, we can use querySelector to select the first element that matches a CSS selector:
var firstParagraph = document.querySelector('p');
And if we need all the elements that match, we use querySelectorAll:
var allParagraphs = document.querySelectorAll('p');
You are ready to start manipulating the DOM with these simple methods. Go ahead and experiment, as practice leads to mastery! In the next module, we will discuss how to change and interact with these specific elements. I’ll see you there.