JavaScript Code

JavaScript – Find Elements by CSS Selector


Tutorials using JS

Find Elements by CSS Selector

to find elements in the document that has a given CSS Selector, use Document.querySelectorAll() function

Syntax

The syntax of querySelectorAll() function is

document.querySelectorAll("css_selector")

where

  • document object is the root node of the HTML document
  • querySelectorAll is the function name
  • css_selector is the value, using which we select elements just like how we select elements when stylising in CSS

the function call returns a NodeList object which is like an array of elements, that has the given class name

Examples

1. find elements whose CSS selector is p.note

in the following document, we have four paragraphs. when user clicks on Click Me button, we find the elements by CSS selector 'p.note' (paragraphs with the class name as ‘note’) and change their background color to yellow

<!DOCTYPE html>
<html>
<body>
<h1>JavaScript Tutorial</h1>
<h2>Find Elements by CSS Selector</h2>
<button id="myBtn">Click Me</button>
<p>This is a paragraph.</p>
<p class="message">This is second paragraph.</p>
<p class="note">This is third paragraph.</p>
<p class="note">This is another paragraph.</p>

<script>
//set onclick listener for #myBtn
document.getElementById("myBtn").addEventListener("click", function() {
    //get all the elements whose class name is 'note'
    const paraNotes = document.querySelectorAll('p.note');
    for ( let i = 0; i < paraNotes.length ; ++i) {
        paraNotes[i].style.background = 'yellow';
    }
});
</script>

</body>
</html>


Copyright @2022