Selecting DOM Elements in JavaScript
Tags: javascript, beginners, codenewbie, womenintech
Published: 2021-01-24 21:50:09

DOM stands for Document Object Model. It represents a document with a logical tree. Each branch of the tree ends in a node, and each node contains objects. 

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/qw5bg9djovrmryjymr5p.png)
_Source: [Launch Code Education](https://education.launchcode.org/intro-to-professional-web-dev/chapters/dom-and-events/dom.html)_

Every operation on the DOM starts with the document object. The DOM allows us to change an element's structure, style, or content.

We'll be examining the following ways to select DOM elements: 

1. getElementById()
2. getElementsByClassName()
3. getElementsByTagName()
4. querySelector()
5. querySelectorAll()


## 1. getElementById()
Id's are usually unique because no two HTML elements should have the same Id. This method is useful when you need to select an element with a specific id on the DOM. 

The `getElementById` returns an element object that describes the DOM element with the specified id. If no element with that `id` exists, it returns `null`.


Let's examine this code snippet
```html
 <div id='parent-1'>
    <div class='child-1'>
      <p>I am the first child of parent 1</p>
      <p>I am the second child of parent 1</p>
    </div>
  </div>
```


```js
// Selecting the element with an id of `parent-1`
const firstParent = document.getElementById("parent-1");
```

> Usually, you'll want to store the selected element in a variable. In this case, our variable is `firstParent`.


##2. getElementsByClassName() 

In HTML, classes can be applied to multiple elements. `getElementsByClassName` is used to select elements that have a  class. It returns an HTML collection of matching elements which is an array-like object.

*In order to turn HTML collections to arrays, simply use `Array.from()`*

Let's examine this code snippet

```html
<div>
  <div id='parent-1'>
    <div class='child-1'>
      <p>I am the first child of parent 1</p>
      <p>I am the second child of parent 1</p>
    </div>
  </div>
  <div id='parent-2'>
    <div class='child-1'>
      <p>I am the first child of parent 2</p>
      <p>I am the second child of parent 2</p>
    </div>
  </div>
</div>;
```

```js
// Selecting the elements with a class of `child-1`
const firstChildElements = document.getElementsByClassName("child-1");
```
> Notice that from our code, 2 elements have classes `child-1`. We are then storing the HTML collection returned in the `firstChildElements` variable.

To transform `firstChildElements` HTML collection into an array, use `Array.from(firstChildElements)`.

*Once you turn the HTML collection into an array, you can now perform array methods on it.*


##3. getElementsByTagName()

The `getElementsByTagName` method returns a collection of an elements's child elements with the specified tag name, as an HTML Collection.

For DOM trees that represent HTML documents, the returned tag name is always in the upper-case form.


```html
<div>
  <div id='parent-1'>
    <div class='child-1'>
      <p>I am the first child of parent 1</p>
      <p>I am the second child of parent 1</p>
    </div>
  </div>
  <div id='parent-2'>
    <div class='child-1'>
      <p>I am the first child of parent 2</p>
      <p>I am the second child of parent 2</p>
    </div>
  </div>
</div>;
```
In this example,
```js
// Selecting elements with the `p` tag
const paragraphs = document.getElementsByTagName("p");
```

> Notice that from our code, 4 elements have the `p` tag. We are storing the HTML collection returned in the variable called `paragraph`.

To transform `paragraphs` HTML collection into an array, use `Array.from(paragraphs)`.

### querySelector()

The `querySelector` allows you to find the **first element** that matches one or more CSS selectors.

```html
<div>
  <div id='parent-1'>
    <div class='child-1'>
      <p>I am the first child of parent 1</p>
      <p>I am the second child of parent 1</p>
    </div>
  </div>
  <div id='parent-2'>
    <div class='child-1'>
      <p>I am the first child of parent 2</p>
      <p>I am the second child of parent 2</p>
    </div>
  </div>
</div>;
```
> When using `querySelector`, you pass in the actual CSS selector, unlike previous methods where you only needed to pass in the text. That is `#parent-1` instead of `parent-1`

```js
// Selecting the first Parent 
const firstParent = document.querySelector("#parent-1");
```

### querySelectorAll()

This is similar to the `querySelector` except that it returns **all the elements** that match the CSS selectors.

The `querySelectorAll` method returns a static NodeList of elements that match the CSS selector. If no element found, it returns an empty NodeList.

```html
<div>
  <div id='parent-1'>
    <div class='child-1'>
      <p>I am the first child of parent 1</p>
      <p>I am the second child of parent 1</p>
    </div>
  </div>
  <div id='parent-2'>
    <div class='child-1'>
      <p>I am the first child of parent 2</p>
      <p>I am the second child of parent 2</p>
    </div>
  </div>
</div>;
```
> When using `querySelectorAll`, you pass in the actual CSS selector, unlike previous methods where you only needed to pass in the text. That is `.child-1` instead of `child-1`
```js
// Selecting all elements that match `child-1` class
const first = document.querySelectorAll(".child-1");
```

*A Nodelist is an array-like object and can be converted to an array using `Array.from()`*

----------------------
Thanks for reading and I hope this post serves as a helpful resource when selecting DOM elements.

I use mostly `querySelector` and `querySelectorAll`. 

* Which of these methods do you use?
* Is there any advantage of using querySelector instead of getElementById or getElementsByClassName? 

Will love to read your comments ❤️