Edit

JavaScript DOM Selectors

How to Select DOM Elements in JavaScript

You can get or modify the HTML content or value by using JavaScript. But, you need to find or select the target HTML element for modify the HTML content.

In the following sections, you will see some of the common ways of selecting the elements.

How to Select the Topmost HTML Elements

The topmost elements in an HTML document are available directly as document properties. For example, the <html> element can be accessed with document.documentElement property, whereas the <head> element can be accessed with document.head property, and the <body> element can be accessed with document.body property. 

How to Select Elements by ID

You can select an element based on its unique ID with the getElementById() method. This is the easiest way to find an HTML element in the DOM tree.

The following example selects and highlight an element having the ID attribute id="paragraph-javascript-dom-select".

Example of Code

<p id="paragraph-javascript-dom-select">This is a paragraph of text.</p>
<p>This is another paragraph of text.</p>
<script>
// Selecting element with id mark 
var match = document.getElementById("paragraph-javascript-dom-select");
// Highlighting element's background
match.style.background = "yellow";
</script>

Output

This is a paragraph of text.

This is another paragraph of text.

How to Select Elements by Class Name

You can use the getElementsByClassName() method to select all the elements having specific class names. This method returns an array-like object of all child elements which have all of the given class names. Let's check out the following example:

Example of Code

<p class="test">This is a paragraph of text.</p>
<div class="block test">This is another paragraph of text.</div>
<p>This is one more paragraph of text.</p>
<hr>
<script>
// Selecting elements with class test
var matches = document.getElementsByClassName("test");
// Displaying the selected elements count
document.write("Number of selected elements: " + matches.length);
// Applying bold style to first element in selection
matches[0].style.fontWeight = "bold";
// Applying italic style to last element in selection
matches[matches.length - 1].style.fontStyle = "italic";   
// Highlighting each element's background through loop
for(var elem in matches) {  
    matches[elem].style.background = "yellow";
}
</script>

Output

This is a paragraph of text.

This is another paragraph of text.

This is one more paragraph of text.