Html get all elements with id

HTML DOM querySelectorAll() Method

Set the background color of the first element with inside of a element:

// Get the element with (a div), then get all elements inside div with >var x = document.getElementById(«myDIV»).querySelectorAll(«.example»);

// Set the background color of the first element with (index 0) in div
x[0].style.backgroundColor = «red»;

More «Try it Yourself» examples below.

Description

The querySelectorAll() method returns a collection of an element’s child elements that match a specified CSS selector(s), as a static NodeList object.

See Also:

Tutorials:

NodeList

A NodeList is an array-like collection (list) of nodes.

The nodes in the list can be accessed by index. The index starts at 0.

The length Poperty returns the number of nodes in the list.

Browser Support

The numbers in the table specifies the first browser version that fully supports the method.

Method
querySelectorAll() 4.0 9.0 3.5 3.2 10.0

Syntax

Parameter Values

Parameter Type Description
CSS selectors String Required. Specifies one or more CSS selectors to match the element. These are used to select HTML elements based on their id, classes, types, attributes, values of attributes, etc.

For multiple selectors, separate each selector with a comma.

Technical Details

DOM Version: Selectors Level 1 Document Object
Return Value: A NodeList object, representing all descendant elements of the current element that matches a specified CSS selector(s). The NodeList is a static collection, meaning that changes in the DOM has NO effect in the collection.

More Examples

Example

Get all

elements inside a element, and set the background color of the first

element (index 0):

// Get the element with (a div), then get all p elements inside div
var x = document.getElementById(«myDIV»).querySelectorAll(«p»);

// Set the background color of the first

element (index 0) in div
x[0].style.backgroundColor = «red»;

Example

Get all

elements in a with and set the background of the first

element:

// Get the element with (a div), then get all p elements with inside div
var x = document.getElementById(«myDIV»).querySelectorAll(«p.example»);

// Set the background color of the first

element with (index 0) in div
x[0].style.backgroundColor = «red»;

Example

Find out how many elements with there are in a element (using the length property of the NodeList object):

/* Get the element with (a div), then get all p elements with inside div, and return the number of elements found */
var x = document.getElementById(«myDIV»).querySelectorAll(«.example»).length;

Example

Set the background color of all elements with in a element:

// Get the element with (a div), then get all elements with inside div
var x = document.getElementById(«myDIV»).querySelectorAll(«.example»);

// Create a for loop and set the background color of all elements with in div
var i;
for (i = 0; i < x.length; i++) x[i].style.backgroundColor = "red";
>

Example

Set the background color of all

elements in a element:

// Get the element with (a div), then get all p elements inside div
var x = document.getElementById(«myDIV»).querySelectorAll(«p»);

// Create a for loop and set the background color of all p elements in div
var i;
for (i = 0; i < x.length; i++) x[i].style.backgroundColor = "red";
>

Источник

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.

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 17, 2023 by MDN contributors.

Your blueprint for a better internet.

Источник

JavaScript HTML DOM Elements

This page teaches you how to find and access HTML elements in an HTML page.

Finding HTML Elements

Often, with JavaScript, you want to manipulate HTML elements.

To do so, you have to find the elements first. There are several ways to do this:

  • Finding HTML elements by id
  • Finding HTML elements by tag name
  • Finding HTML elements by class name
  • Finding HTML elements by CSS selectors
  • Finding HTML elements by HTML object collections

Finding HTML Element by Id

The easiest way to find an HTML element in the DOM, is by using the element id.

This example finds the element with id=»intro» :

Example

If the element is found, the method will return the element as an object (in element).

If the element is not found, element will contain null .

Finding HTML Elements by Tag Name

This example finds all

elements:

Example

This example finds the element with id=»main» , and then finds all

elements inside «main» :

Example

Finding HTML Elements by Class Name

If you want to find all HTML elements with the same class name, use getElementsByClassName() .

This example returns a list of all elements with class=»intro» .

Example

Finding HTML Elements by CSS Selectors

If you want to find all HTML elements that match a specified CSS selector (id, class names, types, attributes, values of attributes, etc), use the querySelectorAll() method.

This example returns a list of all

elements with class=»intro» .

Example

Finding HTML Elements by HTML Object Collections

This example finds the form element with id=»frm1″ , in the forms collection, and displays all element values:

Example

const x = document.forms[«frm1»];
let text = «»;
for (let i = 0; i < x.length; i++) text += x.elements[i].value + "
«;
>
document.getElementById(«demo»).innerHTML = text;

The following HTML objects (and object collections) are also accessible:

Источник

Читайте также:  Python modulenotfounderror no module named numpy
Оцените статью