Advanced selectors of the DOM element in JavaScript
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.