Javascript select all elements with class

Element: querySelectorAll() method

The Element method querySelectorAll() returns a static (not live) NodeList representing a list of elements matching the specified group of selectors which are descendants of the element on which the method was called.

Syntax

querySelectorAll(selectors) 

Parameters

A string 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 that the selectors are applied to the entire document, not just the particular element on which querySelectorAll() is called. To restrict the selector to the element on which querySelectorAll() is called, include the :scope pseudo-class at the start of the selector. See the selector scope example.

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.

Читайте также:  Build python with tkinter

Return value

A non-live NodeList containing one Element object for each descendant node that matches at least one of the specified selectors.

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

Exceptions

Thrown if the syntax of the specified selectors string is not valid.

Examples

dataset selector & attribute selectors

section class="box" id="sect1"> div class="funnel-chart-percent1">10.900%div> div class="funnel-chart-percent2">3700.00%div> div class="funnel-chart-percent3">0.00%div> section> 
// dataset selectors const refs = [ . document.querySelectorAll(`[data-name*="funnel-chart-percent"]`), ]; // attribute selectors // const refs = [. document.querySelectorAll(`[class*="funnel-chart-percent"]`)]; // const refs = [. document.querySelectorAll(`[class^="funnel-chart-percent"]`)]; // const refs = [. document.querySelectorAll(`[class$="funnel-chart-percent"]`)]; // const refs = [. document.querySelectorAll(`[class~="funnel-chart-percent"]`)]; 

Obtaining a list of matches

const matches = myBox.querySelectorAll("p"); 
const matches = myBox.querySelectorAll("div.note, div.alert"); 

Here, we get a list of the document’s

elements whose immediate parent element is a with the class «highlighted» and which are located inside a container whose ID is «test» .

const container = document.querySelector("#test"); const matches = container.querySelectorAll("div.highlighted > p"); 
const matches = document.querySelectorAll("iframe[data-src]"); 

Here, an attribute selector is used to return a list of the list items contained within a list whose ID is «userlist» which have a «data-active» attribute whose value is «1» :

const container = document.querySelector("#userlist"); const matches = container.querySelectorAll("li[data-active='1']"); 

Accessing the matches

Once the NodeList of matching elements is returned, you can examine it just like any array. If the array is empty (that is, its length property is 0 ), then no matches were found.

Otherwise, you can use standard array notation to access the contents of the list. You can use any common looping statement, such as:

const highlightedItems = userList.querySelectorAll(".highlighted"); highlightedItems.forEach((userItem) =>  deleteUser(userItem); >); 

Note: NodeList is not a genuine array, that is to say it doesn’t have array methods like slice , some , map , etc. To convert it into an array, try Array.from(nodeList) .

Selector scope

The querySelectorAll() method applies its selectors to the whole document: they are not scoped to the element on which the method is called. To scope the selectors, include the :scope pseudo-class at the start of the selector string.

HTML

In this example the HTML contains:

  • two buttons: #select and #select-scope
  • three nested elements: #outer , #subject , and #inner
  • a element which the example uses for output.
button id="select">Selectbutton> button id="select-scope">Select with :scopebutton> div id="outer"> .outer div id="subject"> .subject div id="inner">.innerdiv> div> div> pre id="output">pre> 
div  margin: 0.5rem; padding: 0.5rem; border: 3px #20b2aa solid; border-radius: 5px; font-family: monospace; > pre, button  margin: 0.5rem; padding: 0.5rem; > 

JavaScript

In the JavaScript, we first select the #subject element.

When the #select button is pressed, we call querySelectorAll() on #subject , passing «#outer #inner» as the selector string.

When the #select-scope button is pressed, we again call querySelectorAll() on #subject , but this time we pass «:scope #outer #inner» as the selector string.

const subject = document.querySelector("#subject"); const select = document.querySelector("#select"); select.addEventListener("click", () =>  const selected = subject.querySelectorAll("#outer #inner"); output.textContent = `Selection count: $selected.length>`; >); const selectScope = document.querySelector("#select-scope"); selectScope.addEventListener("click", () =>  const selected = subject.querySelectorAll(":scope #outer #inner"); output.textContent = `Selection count: $selected.length>`; >); 

Result

When we press «Select», the selector selects all elements with an ID of inner that also have an ancestor with an ID of outer . Note that even though #outer is outside the #subject element, it is still used in selection, so our #inner element is found.

When we press «Select with :scope», the :scope pseudo-class restricts the selector scope to #subject , so #outer is not used in selector matching, and we don’t find the #inner element.

Specifications

Browser compatibility

BCD tables only load in the browser

See also

  • Locating DOM elements using selectors
  • Attribute selectors in the CSS Guide
  • Attribute selectors in the MDN Learning Area
  • Element.querySelector()
  • Document.querySelector() and Document.querySelectorAll()
  • DocumentFragment.querySelector() and DocumentFragment.querySelectorAll()

Found a content problem with this page?

This page was last modified on Jul 22, 2023 by MDN contributors.

Your blueprint for a better internet.

Источник

Document: getElementsByClassName() method

The getElementsByClassName method of Document interface returns an array-like object of all child elements which have all of the given class name(s).

When called on the document object, the complete document is searched, including the root node. You may also call getElementsByClassName() on any element; it will return only elements which are descendants of the specified root element with the given class name(s).

Warning: This is a live HTMLCollection . Changes in the DOM will reflect in the array as the changes occur. If an element selected by this array no longer qualifies for the selector, it will automatically be removed. Be aware of this for iteration purposes.

Syntax

getElementsByClassName(names) 

Parameters

A string representing the class name(s) to match; multiple class names are separated by whitespace.

Return value

A live HTMLCollection of found elements.

Examples

Get all elements that have a class of ‘test’:

.getElementsByClassName("test"); 

Get all elements that have both the ‘red’ and ‘test’ classes:

.getElementsByClassName("red test"); 

Get all elements that have a class of ‘test’, inside of an element that has the ID of ‘main’:

.getElementById("main").getElementsByClassName("test"); 

Get the first element with a class of ‘test’, or undefined if there is no matching element:

.getElementsByClassName("test")[0]; 

We can also use methods of Array.prototype on any HTMLCollection by passing the HTMLCollection as the method’s this value. Here we’ll find all div elements that have a class of ‘test’:

const testElements = document.getElementsByClassName("test"); const testDivs = Array.prototype.filter.call( testElements, (testElement) => testElement.nodeName === "DIV", ); 

Get the first element whose class is ‘test’

This is the most commonly used method of operation.

html lang="en"> body> div id="parent-id"> p>hello world 1p> p class="test">hello world 2p> p>hello world 3p> p>hello world 4p> div> script> const parentDOM = document.getElementById("parent-id"); const test = parentDOM.getElementsByClassName("test"); // a list of matching elements, *not* the element itself console.log(test); // HTMLCollection[1] const testTarget = parentDOM.getElementsByClassName("test")[0]; // the first element, as we wanted console.log(testTarget); // 

hello world 2

script> body> html>

Multiple Classes Example

document.getElementsByClassName works very similarly to document.querySelector and document.querySelectorAll . Only elements with ALL of the classNames specified are selected.

HTML

span class="orange fruit">Orange Fruitspan> span class="orange juice">Orange Juicespan> span class="apple juice">Apple Juicespan> span class="foo bar">Something Randomspan> textarea id="resultArea" style="width:98%;height:7em">textarea> 

JavaScript

// getElementsByClassName only selects elements that have both given classes const allOrangeJuiceByClass = document.getElementsByClassName("orange juice"); let result = "document.getElementsByClassName('orange juice')"; for (let i = 0; i  allOrangeJuiceByClass.length; i++)  result += `\n $allOrangeJuiceByClass[i].textContent>`; > // querySelector only selects full complete matches const allOrangeJuiceQuery = document.querySelectorAll(".orange.juice"); result += "\n\ndocument.querySelectorAll('.orange.juice')"; for (let i = 0; i  allOrangeJuiceQuery.length; i++)  result += `\n $allOrangeJuiceQuery[i].textContent>`; > document.getElementById("resultArea").value = result; 

Result

Specifications

Browser compatibility

BCD tables only load in the browser

Found a content problem with this page?

This page was last modified on Jul 7, 2023 by MDN contributors.

Your blueprint for a better internet.

Источник

HTML DOM Document querySelectorAll()

The querySelectorAll() method returns all elements that matches a CSS selector(s).

The querySelectorAll() method returns a NodeList.

The querySelectorAll() method throws a SYNTAX_ERR exception if the selector(s) is invalid

Tutorials:

QuerySelector Methods:

GetElement Methods:

The Difference Between an HTMLCollection and a NodeList

A NodeList and an HTMLcollection is very much the same thing.

Both are array-like collections (lists) of nodes (elements) extracted from a document. The nodes can be accessed by index numbers. The index starts at 0.

Both have a length property that returns the number of elements in the list (collection).

An HTMLCollection is a collection of document elements.

A NodeList is a collection of document nodes (element nodes, attribute nodes, and text nodes).

HTMLCollection items can be accessed by their name, id, or index number.

NodeList items can only be accessed by their index number.

The getElementsByClassName() and getElementsByTagName() methods return a live HTMLCollection.

The querySelectorAll() method returns a static NodeList.

The childNodes property returns a live NodeList.

Syntax

Parameters

Parameter Description
CSS selectors Required.
One or more CSS selectors.

CSS selectors select HTML elements based on id, classes, types, attributes, values of attributes etc.
For a full list, go to our CSS Selectors Reference.

Return Value

Type Description
Object A NodeList object with the elements that matches the CSS selector(s).
If no matches are found, an empty NodeList object is returned.

More Examples

Add a background color to the first

element:

Add a background color to the first

element with >

Set the background color of all elements with >

const nodeList = document.querySelectorAll(«.example»);
for (let i = 0; i < nodeList.length; i++) nodeList[i].style.backgroundColor = "red";
>

Set the background color of all

elements:

let nodeList = document.querySelectorAll(«p»);
for (let i = 0; i < nodeList.length; i++) nodeList[i].style.backgroundColor = "red";
>

const nodeList = document.querySelectorAll(«a[target]»);
for (let i = 0; i < nodeList.length; i++) nodeList[i].style.border = "10px solid red";
>

Set the background color of every

element where the parent is a element:

const nodeList = document.querySelectorAll(«div > p»);
for (let i = 0; i < nodeList.length; i++) nodeList[i].style.backgroundColor = "red";
>

Set the background color of all , and elements:

const nodeList = document.querySelectorAll(«h3, div, span»);
for (let i = 0; i < nodeList.length; i++) nodeList[i].style.backgroundColor = "red";
>

Browser Support

document.querySelectorAll() is a DOM Level 3 (2004) feature.

It is fully supported in all modern browsers:

Chrome Edge Firefox Safari Opera IE
Yes Yes Yes Yes Yes 11

Источник

Оцените статью