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.


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

JavaScript Code: app.js

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

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

for(let paragraph of paragraphs){ = 'white';

Recommended Posts