There are several ways to grab DOM elements using the document object. We can use the id…
This will grab the DOM element that has the ID we pass to the getElementById function and stores it in the variable.
We can get elements by the class name…
This will grab all the elements with the class name passed to the getElementsByClassName method. It will return them as an array and store them in the variable. This is the largest difference between grabbing DOM elements by ID versus class. Grabbing them by ID only returns the one element because there can (should) only be one element with that ID on the page. The can be multiple elements with the class name though.
We can also grab by tag name…
In this example, we are getting all of the paragraph elements on the page and storing them as an array in the variable.
We can also utilize css selectors with two additional methods…querySelector and querySelectorAll…
In this example, we can grab any element by a css selector. I have the ID in the method, but we can pass a class, a tag or a combination of those. For example, if we would like a paragraph tag with the ID of intro…
We can also grab several elements…
Again, we can use css selectors. This difference here is we can grab several elements and they return as an array. For example, if we wish to grab all images that have a class of gallery…