JavaScript Tutorial Series: Selecting elements
Published: 2023-03-02 20:28:49

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:

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

```

```JavaScript
//(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);
```


![getElementByID](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/8kmjxfe0ysjfcjzlc6y3.png)

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.

```HTML
<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">
```

```JavaScript
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);
}
```

![getElementsByName](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/0sa1q7qnibb2ym3yuwwm.png)

## 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:

```HTML
<!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>
```

```JavaScript
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
```

![getElementsByTagName](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/8r09qxvhdzcej9y4ifzr.png)

## 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. 

```HTML
<ul>
   <li class="lang">JavaScript</li>
   <li class="lang">PHP</li>
   <li class="lang">Nodejs</li>
</ul>
```

```JavaScript
let listItems = document.getElementsByClassName("lang");
for (let i = 0; i < listItems.length; i++) {
   console.log(listItems[i].textContent);
 }

console.log(listItems);
```

![getElementsByClassName](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/j6qdzikzd3ir1ophj1bc.png)

## 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:

```HTML
<ul>
  <li class="lang">JavaScript</li>
  <li class="lang">PHP</li>
  <li class="lang">Nodejs</li>
</ul>
```

```JavaScript
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);
}
```

![querySelector and querySelectorAll](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/vazlj1ngvei18lele51f.png)