
While creating interactive content with JavaScript, you will often find yourself needing to access various HTML elements in order to make changes to them. We'll go through some of the main ways you can grab elements in the DOM, and how you can make use of what they hold.
Different Types of Selectors
ID
If you want to manipulate one single element, the easiest and most straight-forward approach is to find that element byid
. Only one HTML element can have a specificid
attribute, and each ID is unique to one element.
Class
Multiple elements can be grouped together when they are given the sameclass
name. An example would be if you have multiple buttons that serve the purpose of deleting content, and you want all of those buttons to be manipulated in the same manner.
Tag
Some common tags in HTML arebody
,h1
,p
,div
,span
, andimg
, though there are numerous others. Another DOM selector istagName
, which selects elements based on the type of element they are.
Accessing an Element by ID
In order to access an element with a specificid
, you have a few options. You can either use:
document.getElementById('element-id')
or
document.querySelector('#element-id')
Either option will search the entire document and return the element with a matchingid
as an object. If no element with the givenid
is found,null
will be returned. If you encounter aTypeError: Cannot read properties of null
, it is likely that no element with thatid
was found.
You can also use these methods to create a variable, and then manipulate the DOM by calling that variable.
let foundElement = document.getElementById('first-header')foundElement.style.color = 'blue'
If an element does not exist in the HTML file and is created using JavaScript, you can still give that element anid
using JavaScript with the following syntax:
let createdWithJsElement = document.createElement('p')createdWithJsElement.id = 'js-element'
Accessing an Element by ClassName
Similar to accessing an element byid
, you have a few choices for selecting elements byclass
. You can access elements byclass
name with the following methods.
document.querySelector('.element-class')
This will return only thefirst element that matches the specifiedclass
name.
document.getElementsByClassName('element-class')
The use ofgetElementsByClassName
will return a liveHTMLCollection
of all the elements matching thatclass
.
document.querySelectorAll('.element-class')
Using thequerySelectorAll
method will return a staticNodeList
of all the elements matching that class. Distinguishing between aNodeList
and anHTMLCollection
is a whole other topic which you can explorehere.
Note the use of adot prior to theclass
name, as opposed to thehash-tag prior to doing a query selector on anid
.
In order to manipulate every element that is returned from thegetElementsByClassName
orquerySelectorAll
methods, you'll need to run afor loop
to iterate the array-like object and make the desired changes to each element.
let allButtons = document.getElementsByClassName('button')function testButtons () { for (let i = 0; i < allButtons.length; i++) { console.log(`I am button ${[i+1]}`); }}
You can create or change an element'sclass
, or otherattribute
, by accessing that element by its[index]
.
allButtons[5].className = 'delete-button'
Accessing an Element by TagName
Yet another way to select elements in the DOM is to select the elements by theirtag
name.
let allParagraphs = document.getElementsByTagName('p')
You can get even more specific with your search for specific elements based ontag name
. Suppose you want to change the color of the text in all the paragraphs of a "Skills" section. You can search for elements bytag name
within a specific div.
const mySkills = document.getElementById("skills-div");const skillParagraphs = mySkills.getElementsByTagName("p");
Like when thegetElementsByClassName
method is called,getElementsByTagName
will return a live HTML collection of elements. This can be iterated over with afor loop
just like the list of elements gathered with thegetElementsByClassName
method.
Wrapping It Up
If you can't precisely locate elements, you'll have difficulty making your JavaScript code come to life. These selectors are just the tip of the iceberg for making your creations dynamic.
Top comments(0)
For further actions, you may consider blocking this person and/orreporting abuse