Here’s What You Need To Know About JavaScript DOM Selectors
Posted by TotalDCNow that we already covered what exactly DOM is in JavaScript, let’s dive a bit deeper and talk about JavaScript DOM Selectors. What they are and how you can use them.
Selecting DOM Elements In JavaScript
As you may know, JavaScript is used to modify the content or value of the HTML elements on the webpage and to apply some effects for example show, hide or do some kind of animations etc. But before you can perform all of this you need to find or select the target HTML elements. In this article we will see some of the ways to select the elements on the page and do some stuff with them using JavaScript.
How To Select The Top Elements Using JavaScript
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, and the <head> element can be accessed with document.head property, <body> element is accessed with document.body. Here’s a simple example for you:
<!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
console.log(document.documentElement.getAttribute("lang"));
// Set background color of body element
document.body.style.background = "yellow";
// Display tag name of the head element's first child
console.log(document.head.firstElementChild.nodeName);
</script>
</body>
</html>
Keep in mind that if you use document.body before the <body> tag, it will return null instead of the body element because at the point at which the script is executed <body> tag was not parsed by the browser.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>JS Document.body Demo</title>
<script>
console.log("From HEAD: " + document.body);
</script>
</head>
<body>
<script>
console.log("From BODY: " + document.body);
</script>
</body>
</html>
How To Select Elements By ID Using JavaScript
You can select an element based on its unique ID with 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=”marked”.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>JS Select Element by ID</title>
</head>
<body>
<p id="marked">This is a paragraph of text.</p>
<p>This is another paragraph of text.</p>
<script>
// Selecting element with id mark
let match = document.getElementById("marked");
// 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, or null if no matching element was found in the document.
How To Select Elements By Class Name Using JavaScript
Similar to previous method, you can use the getElementByClassName() method. This method will select all the elements that have specific class name. This method returns an array-like object of all elements which have required class name. Let’s check out the following example:
<!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
let matches = document.getElementsByClassName("test");
// Displaying the selected elements count
console.log("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(let elem in matches) {
matches[elem].style.background = "yellow";
}
</script>
</body>
</html>
How To Select Elements By Tag Name Using JavaScript
Another way to select elements using Javascript is with getElementsByTagName() method. This method also returns an array-like object of all elements with required 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
let matches = document.getElementsByTagName("p");
// Printing the number of selected paragraphs
console.log("Number of selected elements: " + matches.length);
// Highlighting each paragraph's background through loop
for(let elem in matches) {
matches[elem].style.background = "yellow";
}
</script>
</body>
</html>
How To Select Elements With CSS Selectors Using JavaScript
For this you can use the querySelectorAll() method. It will select elements that matches the specified CSS selector. This method returns a list of all the elements that matches the specified selectors. You can examine it just like any array. Let’s look at the example:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>JS Select Elements with CSS Selectors</title>
</head>
<body>
<ul>
<li>Donut</li>
<li class="tick">Coffee</li>
<li>Cake</li>
</ul>
<script>
// Selecting all li elements
let matches = document.querySelectorAll("ul li");
// Printing the number of selected li elements
console.log("Number of selected elements: " + matches.length + "<hr>")
// Printing the content of selected li elements
for(let elem of matches) {
console.log(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>