536 total views, 1 views today
Select many nodes / querySelectorAll (mdn)
We will discuss more about static vs live nodes in the upcoming lessons.
elementList = parentNode.querySelectorAll(selectors);
DOMString 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: If the specified
selectors include a CSS pseudo-element, the returned list is always empty.
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