JavaScript is frequently used to access or change the content or value of HTML elements on the page, and to apply effects like showing, hiding, animations, etc. However, before you can do any of this, you need to find or select the target HTML element.
In the following sections, you will learn some common ways to select elements on a page and manipulate them using JavaScript.
The topmost elements in an HTML document can be accessed directly as document
properties. For example, the <html>
element can be accessed with the document.documentElement
property, the <head>
element with the document.head
property, and the <body>
element with the document.body
property. Here's 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>
But, be cautious. 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 where the script is executed, the <body>
tag hasn't been parsed by the browser, so document.body
is truly null
at that time.
Here's an example to illustrate 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>
You can select an element based on its unique ID using the getElementById()
method. This is the simplest way to find an HTML element in the DOM tree.
The following example selects and highlights an element with the ID attribute id="mark"
.
<!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, or null
if no matching element was found in the document.
Note: Any HTML element can have an id
attribute. The value of this attribute must be unique within a page, meaning no two elements on the same page can have the same ID.
Similarly, you can use the getElementsByClassName()
method to select all elements with specific class names. This method returns an array-like object of all child elements that have all of the given class names. Let's look at 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
var matches = document.getElementsByClassName("test");
// Displaying the number of selected elements
document.write("Number of selected elements: " + matches.length);
// Applying bold style to the first element in the selection
matches[0].style.fontWeight = "bold";
// Applying italic style to the last element in the selection
matches[matches.length - 1].style.fontStyle = "italic";
// Highlighting each element's background in a loop
for(var elem of matches) {
matches[elem].style.background = "yellow";
}
</script>
</body>
</html>
You can also select HTML elements by tag name using the getElementsByTagName()
method. This 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 in a loop
for(var elem of matches) {
matches[elem].style.background = "yellow";
}
</script>
</body>
</html>
You can use the querySelectorAll()
method to select elements that match specified CSS selectors. CSS selectors provide a very powerful and efficient way of selecting HTML elements in a document. Check out the CSS tutorial section to learn more about them.
This method returns a list of all the elements that match the specified selectors. You can work with it just like an array, as shown in the following 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 the 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 like :first-child
, :last-child
, :hover
, etc. However, for CSS pseudo-elements such as ::before
, ::after
, ::first-line
, etc., this method always returns an empty list.