Consider following html code
<ul>
<li id=“one” class=“main”>Item 1</li>
<li id=“two” class=“main”>Item 2</li>
<li id=“three” class=“main”>Item 3</li>
<li id=“four”>Item 4</li>
</ul>
Following dom tree will be constructed based on above html code
ul
|
| | | |
li li li li
| | | |
Item 1 Item 2 Item 3 Item 4
We can select elements from DOM tree with the help of CSS selectors. This is possible by means of two javascript methods viz querySelector()
and querySelectorAll()
.
querySelector() method returns the first element that matches the given css selector from the DOM.
document.querySelector('li.main')
returns the first li
element who's class is main
document.querySelector('#two')
returns the element with id two
NOTE: If no element is found null
is returned. If the selector string contains a CSS pseudo-element, the return will be null
.
querySelectorAll() method returns all the elements that matches the given css selector from the DOM.
document.querySelectorAll('li.main')
returns a node list containing all the li
elements who's class is main
.
NOTE: If no element is found an empty node list is returned. If the selectors string contains a CSS pseudo-element, the returned elementList will be empty