How to access an HTML element using JavaScript in different ways

Overview

When we want to access HTML elements in JavaScript, we use the Document Object Model (DOM)'s methods.

What is the DOM?

DOM is a data representation of the objects that make up a document's structure and content.

We can access HTML elements, that are h1,h2,h3, p, in JavaScript using five different ways:

  • getElementById
  • getElementByClassName
  • getElementByName
  • getElement ByTagName
  • getElementbyCSSSelector
  1. The getElementById method

We use the getElementById method to access the ID of a particular HTML element, where we parse in the ID to the method then we use the inner HTML property to set the element's innerHTML property to whatever we want.

The example below demonstrates how we use the getElementById():

2. The getElementByClassName method

Here we access elements using a particular className, we can access multiple HTML elements bearing the same classNames and also edit some of its properties.

#include <iostream>
using namespace std;
int main() {
// your code goes here
cout << "Hello World";
return 0;
}
#include <iostream>
using namespace std;
int main() {
// your code goes here
cout << "Hello World";
return 0;
}
Console

Using the solution above we get all the elements with the defined class, and store them in a variable x, which is a nodeList, so we can't perform array operations on it. We convert the nodeList to an array ( using Array.from()) so we can perform a forEach and change the innerHTML property to whatever we want.

3. The getElementsByName method:

Similarly to the getElementById, we can parse in a name property to various HTML tags like <h1 name="h1-name"></h1>. We can access HTML properties this way and perform various operations on it.

However, getElementsByName returns a nodeList of elements with a particular name.

In the example below, we'll use our code to change the innerHTML Value of any tag with the property of name="h1-name" .

Console

4. The getElementByTagName method

As the name implies, it is very similar to the getElementByName but this time instead of the name property we are accessing the tagName directly.

In the example below, we convert the nodeList to an array and add a className of styled to the array after looping through each element with the tagName, "div".

5. The getElementByCssSelector method

The querySelector method returns the first element in the document that matches the supplied selection (or collection of selectors). Null is returned if no matches are found.

We can either access the element using class (.className) or ID (#elementsId) as parameters into the querySelector method.

Free Resources