Getting the DOM element in JavaScript

Now we will learn how to get the page DOM elements in order to perform some manipulations with them in the future.

Let's have some button:

<input id="button" type="submit">

Let's get a reference to this button into a variable. To do this, use the querySelector method of the special object document. This method takes a CSS selector as a parameter and returns a reference to the element found with this selector.

Our button has an attribute id with the value button. So we can find this button by the selector #button. So, let's find our button and write a reference to it into a variable:

let button = document.querySelector('#button'); console.log(button);

Given 3 paragraphs:

<p id="elem1">1</p> <p id="elem2">2</p> <p id="elem3">3</p>

Put the reference to each of the paragraphs in a separate variable and print the contents of each of these variables to the console.

More advanced selectors

Let's do something more complicated. Let, for example, we have the following HTML code:

<div id="parent"> <input> </div>

Let's get a reference to the input located inside the block #parent:

let elem = document.querySelector('#parent input'); console.log(elem);

As you can see, we got our input using the #parent input selector. In fact, all inputs that are in #parent match this CSS selector.

Let, for example, we have two such inputs:

<div id="parent"> <input value="1"> <input value="2"> </div>

Then, if we write the selector #parent input in the CSS code, it will affect both of our inputs:

#parent input { color: red; }

The querySelector method, however, does not work that way. It always gets only one element - the first one that matches the specified selector. Let's look at an example. Let's say we have inputs with class elem:

<input class="elem"> <input class="elem">

Let's get the first of these inputs:

let elem = document.querySelector('.elem'); console.log(elem); // here will be the first input

Given the following HTML:

<div id="block"> <p>1</p> <p>2</p> </div>

Get a reference to the first paragraph from a div with id equal to block.

Given the following HTML:

<div class="block"> <p>1</p> <p>2</p> </div>

Get a reference to the first paragraph from a div with the class block.

Given the following HTML:

<p class="www">text</p> <p class="www">text</p>

Get a reference to the first paragraph with the class www.