DOM (Document Object Model) Selector
Photo by KOBU Agency on Unsplash
DOM (Document Object Model) Selector is used to select elements from a web page. Observe the script below.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Sample DOM</title>
</head>
<body>
<header>
<h3>Blog pembelajaran Javascript</h3>
</header>
<section id="content">
<div id="sidebar" class="sidebar-left">
<h3 class="title">Categories</h3>
<ul>
<li>Pemrograman</li>
<li>Permainan</li>
<li>Sport</li>
<li>Umum</li>
</ul>
<img src="banner.jpg" alt=""/>
</div>
<div id="article">
<h3 class="title">Mengenal DOM</h3>
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit.
Odit dolorem fugit magni totam vel iste eius voluptates laborum ullam doloremque,
vero iusto, suscipit cumque. Hic nulla tempora ratione, est consequuntur!</p>
</div>
</section>
</body>
</html>
In the script above, we have several elements, including heading, list, image, paragraph, etc. How do we select the word ‘Sport’ in the list above using JavaScript? Or how can we change the title ‘Mengenal DOM’ using JavaScript?
To answer all these questions, we first need to perform an element selection process. This process aims to modify attributes, add classes, change styles, text, and many more changes that can be made. To perform this process, we need an identifier for an element, which we call a DOM Selector.
In a previous article, I wrote about CSS Selectors. What is a CSS Selector? How does it work? What is its relationship with the DOM Selector? To satisfy your curiosity, you can visit the link to revisit CSS Selectors.
In JavaScript, DOM Selection can be done in several ways, including:
1. Get Element by ID
Get Element by ID is used to select elements by using the ID on the element. The syntax used is:
document.getElementById('nama Id')
The syntax above will return `null` if no element with that ID is found. Example of usage:
var sidebar = document.getElementById("sidebar");
sidebar.style.width="33%"; // mengganti properti width menjadi 33%
Note: The element ID must be unique within a web page. If there are multiple elements with the same ID, one of them will not be processed. However, this is different when using an iframe since iframes are essentially different pages.
2. Get Element by Class Attribute
Get Element by Class is used to select elements by using a class on an element. The syntax used is:
document.getElementsByClassName('namaKelas')
The syntax above will select all elements with the class name ‘class_name’. This selector returns a list/collection in the form of an array. Remember the concept of class from CSS? The class value in an element can contain several classes separated by commas. For example: “aa abb”, which means the element has both “aa” and “bb” classes. See the example below:
<p class="aa">1</p>
<p class="bb">2</p>
<p class="bb aa">3</p>
<p class="bb cc aa">4</p>
<script>
// the elements that will be selected are 3 and 4
var selection = document.getElementsByClassName("aa bb");
// if we want to select number 3 only, and change its color to red
selection[0].style.color = "red";
</script>
3. Get Element by Name
Get element by Name is used to select elements by using the name attribute on the element/tag (name=”name_value”). The syntax used is:
document.getElementsByName('Name')
Like getElementByClassName, this selector also returns a list/collection in the form of an array. Observe the example HTML below:
<p name="abc">1</p>
<div class="zz" name="xyz">2</div>
<div class="zz" name="xyz">3</div>
<form>
<input name="xyz" type="text" size="20">
</form>
The JavaScript code to select the element with the name “xyz” on the second element:
var xyz = document.getElementsByName("xyz");
xyz[1].style.color="red"; // make the first one red
4. Get Element by Tag Name
Get element by tag name is used to select elements by the name of the tag/element in HTML. Examples of tag names include: div, header, footer, section, ol, li, etc. The syntax used is:
document.getElementsByTagName('Name')
Like the previous selectors, this also returns a list/collection in the form of an array. Observe the example below:
var list = document.getElementsByTagName("p"); // selects all p tags
list.length; // counts the number of p elements on the HTML page
list[0].style.color = "red"; // selects the first paragraph and changes its color to red
Note: getElementsByClassName, getElementsByName, and getElementsByTagName are not unique, so multiple elements with the same key may exist in a page. Therefore, the return will be a list array.
5. Get Elements by CSS Selector
Get element by CSS Selector selects elements using a CSS selector. The syntax used to select elements with this CSS Selector is:
document.querySelector(css_selector)
The syntax above is used to select the first element that matches the CSS selector we use.
document.querySelectorAll(css_selector)
The syntax above is used to select all elements that match the CSS selector we use. Observe the following example:
let el = document.querySelector(".kuning");
el.style.background = 'yellow';
el.style.padding = '10px';
let ell = document.querySelectorAll(".biru");
for(let i = 0; i < ell.length; i++) {
ell[i].style.padding = '10px';
ell[i].style.background = 'blue';
ell[i].style.color = '#FFF';
}
That’s the explanation of DOM Selectors in JavaScript. If you encounter any mistakes or simply want to ask questions about the material above, feel free to submit them through the discussion form below. I will be happy to receive them.
Thank you