DEV Community

Cover image for JavaScript Tutorial Series: Selecting elements
The daily developer
The daily developer

Posted on • Updated on

JavaScript Tutorial Series: Selecting elements

A fundamental JavaScript task for developing interactive and dynamic web pages is choosing elements from the Document Object Model (DOM). You can retrieve and modify particular elements on a page by selecting them from the DOM. You can, for instance, change an element's text or styling, dynamically add or remove elements, or respond to user actions like mouse clicks and keystrokes. JavaScript offers a number of methods for selecting elements from the DOM, each of which is suitable for a range of situations and uses.

The following are a few approaches:

getElementById()

The Element object that the document.getElementById() method returns is a representation of an HTML element whose id matches a given string.

The document.getElementById() method returns null if the document does not contain the element with the given id.

The document.getElementById() function is a quick way to access an element because each element's id is distinct within an HTML document.

Let's look at an example:

<!DOCTYPE html>
<html>
  <head>
    <title>Selecting elements</title>
  </head>
  <body>
    <div id="container">Hello, World!</div>
    <script src="script.js"></script>
  </body>
</html>

Enter fullscreen mode Exit fullscreen mode
//(script.js)
let Div = document.getElementById("container");

// modify the text content of the element
Div.textContent = "Hello, JavaScript!";

// add a class to the element
Div.classList.add("div-class");

console.log(Div);
Enter fullscreen mode Exit fullscreen mode

getElementByID

In this example, the element with the ID container is chosen and stored in the variable Div using the getElementById() function. The element's text content is then modified using textContent, and a CSS class is added using classList.add(). Remember that the JavaScript code must be placed in a separate file (script.js) and referenced using the src attribute of the script tag in the HTML document.
Do not worry about textContent and classList.add() for now, we will discuss everything in details in the upcoming posts.

getElementsByName()

An HTML document's elements can have a name attribute. Unlike the id attribute, the name attribute allows multiple HTML elements to share the same value.
The function getElementsByName() accepts a name, which is the value of the name attribute of the element, and returns a live NodeList of the element.

<label for="javascript">Javascript</label>
<input type="radio" name="language" value="JavaScript" id="javascript">

<label for="php">PHP</label>
<input type="radio" name="language" value="PHP" id="php">
Enter fullscreen mode Exit fullscreen mode
let radio = document.getElementsByName("language");

// loop through the radio buttons and log their values
for (let i = 0; i < radio.length; i++) {
  console.log(radio[i].value);
}
Enter fullscreen mode Exit fullscreen mode

getElementsByName

getElementsByTagName()

The getElementsByTagName() method takes a tag name as an argument and returns a HTMLCollection of elements that match the given tag name, in the same order they appear in the document.

Let's look at an example:

<!DOCTYPE html>
<html>
  <head>
    <title>Example of getElementsByTagName</title>
  </head>
  <body>
    <ul>
      <li>JavaScript</li>
      <li>PHP</li>
      <li>Nodejs</li>
    </ul>
    <script src="app.js"></script>
  </body>
</html>
Enter fullscreen mode Exit fullscreen mode
let listItems = document.getElementsByTagName("li");

// loop through the list items and log their text content
for (let i = 0; i < listItems.length; i++) {
  console.log(listItems[i].textContent);
}
console.log(listItems); //logs HTMLCollection
Enter fullscreen mode Exit fullscreen mode

getElementsByTagName

getElementsByClassName

The return value from the getElementsByClassName() method is an array-like collection of objects representing the child elements with the specified class name. On the document element or any other element, the getElementsByClassName() method is available.

<ul>
   <li class="lang">JavaScript</li>
   <li class="lang">PHP</li>
   <li class="lang">Nodejs</li>
</ul>
Enter fullscreen mode Exit fullscreen mode
let listItems = document.getElementsByClassName("lang");
for (let i = 0; i < listItems.length; i++) {
   console.log(listItems[i].textContent);
 }

console.log(listItems);
Enter fullscreen mode Exit fullscreen mode

getElementsByClassName

querySelector() and querySelectorAll()

The querySelector() method returns the first element that matches one or more CSS selectors.

The querySelectorAll() method returns a static NodeList of the elements that match the CSS selector and a blank NodeList is returned if there are no elements that match.

Using the same example above:

<ul>
  <li class="lang">JavaScript</li>
  <li class="lang">PHP</li>
  <li class="lang">Nodejs</li>
</ul>
Enter fullscreen mode Exit fullscreen mode
let listItem = document.querySelector(".lang");

let listItems = document.querySelectorAll(".lang");

console.log(listItem);
console.log(listItems);

for (let i = 0; i < listItems.length; i++) {
  console.log(listItems[i].textContent);
}
Enter fullscreen mode Exit fullscreen mode

querySelector and querySelectorAll

Top comments (0)