Mastering JavaScript DOM
About Lesson

Select many nodes / querySelectorAll (mdn)

The Document method querySelectorAll() returns a static (not live) NodeList representing a list of the document’s elements that match the specified group of selectors.

Note: This method is implemented based on the ParentNode mixin’s querySelectorAll() method.

 

We will discuss more about static vs live nodes in the upcoming lessons.

Syntax

elementList = parentNode.querySelectorAll(selectors);

Parameters

selectorsDOMString containing one or more selectors to match against. This string must be a valid CSS selector string; if it’s not, a SyntaxError exception is thrown. See Locating DOM elements using selectors for more information about using selectors to identify elements. Multiple selectors may be specified by separating them using commas.

Note: Characters which are not part of standard CSS syntax must be escaped using a backslash character. Since JavaScript also uses backslash escaping, special care must be taken when writing string literals using these characters. See Escaping special characters for more information.

Return value

A non-live NodeList containing one Element object for each element that matches at least one of the specified selectors or an empty NodeList in case of no matches.

Note: If the specified selectors include a CSS pseudo-element, the returned list is always empty.

Examples

Let’s understand the commonly used selectors with some examples.

Obtaining list of matches

To obtain a list of nodelist that has a CSS class of “.task-item”

const taskNodes = document.querySelectorAll(".task-item");
console.log("by class: ", taskNodes);

To obtain list of nodelist of type “<li>”

const tasks = document.querySelectorAll('li');
console.log("by type: ", tasks); 

You can also select items from already selector nodes. In this case we first select an element by it’s ID and then select all <li>’s using the attribute filter.

The below code should select the 2nd <li> from the list.

var taskList = document.querySelector("#task-list");
var matches = taskList.querySelectorAll("li[data-active='true']");
console.log("by attributes: ", matches);

List of CSS Selector Refrence

https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Selectors

 

Try out the code

CodePen Embed Fallback

 

 

0% Complete