Welcome to another tutorial, here you will learn how to select DOM elements in JavaScript.
JavaScript is commonly used to modify or get the content or value of the HTML elements on the web page, and to apply some effects like show, animations, hide, etc. however, before you can perform any action you need to find or select the target HTML element.
In subsequent sections in this tutorial, we will learn the common ways of selecting the elements on a page and doing something with them using JavaScript.
In an HTML document, the topmost elements are available directly as document properties. For instance, the ‘html’ element can be accessed with ‘document.documentElement property’, while the ‘head’ element can be accessed with ‘document.head property’, and the ‘body’ element can be accessed with ‘document.body property’. Below is an example:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>JS Select Topmost Elements</title>
</head>
<body>
<script>
// Display lang attribute value of html element
alert(document.documentElement.getAttribute("lang")); // Outputs: en
// Set background color of body element
document.body.style.background = "yellow";
// Display tag name of the head element's first child
alert(document.head.firstElementChild.nodeName); // Outputs: meta
</script>
</body>
</html>
However, be careful; if ‘document.body’ is used before the ‘body’ tag (e.g inside the ‘head’), it will return null instead of the body element. This is because, at the point at which the script is executed, the ‘body’ tag was not parsed by the browser, so document.body is truly null at that point.
Here is an example to better understand this:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>JS Document.body Demo</title>
<script>
alert("From HEAD: " + document.body); // Outputs: null (since <body> is not parsed yet)
</script>
</head>
<body>
<script>
alert("From BODY: " + document.body); // Outputs: HTMLBodyElement
</script>
</body>
</html>
In selecting elements by ID, the getElementById() method is used. It is the simplest and easiest way to find an HTML element in the DOM tree.
The example shown below selects and highlight an element having the ID attribute id="mark".
Example:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>JS Select Element by ID</title>
</head>
<body>
<p id="mark">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("mark");
// Highlighting element's background
match.style.background = "yellow";
</script>
</body>
</html>
The getElementById() method will return the element as an object if the matching element was found, and null if no matching element was found within the document.
Note: id attribute is a unique feature of any HTML element. However, the value of this attribute must be unique within a page (i.e no two elements on the same page can have the same ID).
In this case, you can use the getElementsByClassName() method to select any elements having specific class names. The ‘getElementsByClassName()’ method returns an array-like object of any child elements which have all of the given class names. See it in the example below:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>JS Select Elements by Class Name</title>
</head>
<body>
<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>
<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>
</body>
</html>
HTML elements can be selected by tag name using the getElementsByTagName() method. This getElementsByTagName() method also returns an array-like object of all child elements with the given tag name.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>JS Select Elements by Tag Name</title>
</head>
<body>
<p>This is a paragraph of text.</p>
<div class="test">This is another paragraph of text.</div>
<p>This is one more paragraph of text.</p>
<script>
// Selecting all paragraph elements
var matches = document.getElementsByTagName("p");
// Printing the number of selected paragraphs
document.write("Number of selected elements: " + matches.length);
// Highlighting each paragraph's background through loop
for(var elem in matches) {
matches[elem].style.background = "yellow";
}
</script>
</body>
</html>
In this case, the querySelectorAll() method can also be used to select elements that match the specified CSS selector. The CSS selectors are known to provide a powerful and efficient way of selecting HTML elements in a document.
You can check out the CSS tutorial section to learn more about their features and how to use them.
This querySelectorAll() method returns a list of all the elements that match the specified selectors. It can be used to examine it just like any array, as shown in the example:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>JS Select Elements with CSS Selectors</title>
</head>
<body>
<ul>
<li>Bread</li>
<li class="tick">Coffee</li>
<li>Pineapple Cake</li>
</ul>
<script>
// Selecting all li elements
var matches = document.querySelectorAll("ul li");
// Printing the number of selected li elements
document.write("Number of selected elements: " + matches.length + "<hr>")
// Printing the content of selected li elements
for(var elem of matches) {
document.write(elem.innerHTML + "<br>");
}
// Applying line through style to first li element with class tick
matches = document.querySelectorAll("ul li.tick");
matches[0].style.textDecoration = "line-through";
</script>
</body>
</html>
Note: The querySelectorAll() method also supports CSS pseudo-classes such as, :first-child, :last-child, :hover, etc. However, for CSS pseudo-elements like, ::before, ::after, ::first-line, and so on. This method when used always returns an empty list.
You can check out the CSS tutorial section to learn more about their features and how to use them.