JavaScript Basics

JavaScript Advanced

JavaScript Arrays

JavaScript Functions

JavaScript Objects

JavaScript DOM

JavaScript String

How to select HTML elements by CSS Selectors in JavaScript?

JavaScript provides two methods, document.querySelector() and document.querySelectorAll() to select HTML elements based on the CSS selectors.

document.querySelector() method selects the first element that matches the CSS selector whereas document.querySelectorAll() method selects all the HTML elements that matches the CSS selector.

let htmlElement = document.querySelector('css-selector');
let htmlElements = document.querySelectorAll('css-selector');

The following example changes the background color of a div element by selecting it using the document.querySelector() method. In addition to this, all three paragraphs are selected using the document.querySelectorAll() method.

HTML Code

<!DOCTYPE html>
<html>
<head>
  <title>JavaScript document.querySelectorAll() Example</title>
</head>
<body>
  <div id="container">
    <p>First Paragraph.</p>
    <p>Second Paragraph.</p>
    <p>Third Paragraph.</p>
  </div>
</body>
</html>

JavaScript Code: app.js

let container = document.querySelector('#container');

container.style.backgroundColor = "red";

let paragraphs = document.querySelectorAll('#container p');

for(let paragraph of paragraphs){
  paragraph.style.color = 'white';
}

Recommended Posts