Javascript which item selected

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.

Источник

Document: querySelector() method

The Document method querySelector() returns the first Element within the document that matches the specified selector, or group of selectors. If no matches are found, null is returned.

Note: The matching is done using depth-first pre-order traversal of the document’s nodes starting with the first element in the document’s markup and iterating through sequential nodes by order of the number of child nodes.

Syntax

Parameters

A string containing one or more selectors to match. This string must be a valid CSS selector string; if it isn’t, a SyntaxError exception is thrown. See Locating DOM elements using selectors for more about selectors and how to manage them.

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

Return value

An Element object representing the first element in the document that matches the specified set of CSS selectors, or null is returned if there are no matches.

If you need a list of all elements matching the specified selectors, you should use querySelectorAll() instead.

Exceptions

Thrown if the syntax of the specified selectors is invalid.

Usage notes

If the specified selector matches an ID that is incorrectly used more than once in the document, the first element with that ID is returned.

CSS pseudo-elements will never return any elements, as specified in the Selectors API.

Escaping special characters

To match against an ID or selectors that do not follow standard CSS syntax (by using a colon or space inappropriately, for example), you must escape the character with a backslash (» \ «). As the backslash is also an escape character in JavaScript, if you are entering a literal string, you must escape it twice (once for the JavaScript string, and another time for querySelector() ):

div id="foo\bar">div> div id="foo:bar">div> script> console.log("#foo\bar"); // "#fooar" (\b is the backspace control character) document.querySelector("#foo\bar"); // Does not match anything console.log("#foo\\bar"); // "#foo\bar" console.log("#foo\\\\bar"); // "#foo\\bar" document.querySelector("#foo\\\\bar"); // Match the first div document.querySelector("#foo:bar"); // Does not match anything document.querySelector("#foo\\:bar"); // Match the second div script> 

Examples

Finding the first element matching a class

In this example, the first element in the document with the class » myclass » is returned:

const el = document.querySelector(".myclass"); 

Complex selectors

const el = document.querySelector("div.user-panel.main input[name='login']"); 

Negation

As all CSS selector strings are valid, you can also negate selectors:

const el = document.querySelector( "div.user-panel:not(.main) input[name='login']", ); 

This will select an input with a parent div with the user-panel class but not the main class.

Specifications

Browser compatibility

BCD tables only load in the browser

See also

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.

MDN

Support

Our communities

Developers

Visit Mozilla Corporation’s not-for-profit parent, the Mozilla Foundation.
Portions of this content are ©1998– 2023 by individual mozilla.org contributors. Content available under a Creative Commons license.

Источник

HTMLSelectElement

A better way to track changes to the user’s selection is to watch for the change (en-US) event to occur on the . This will tell you when the value changes, and you can then update anything you need to. See the example provided (en-US) in the documentation for the change event for details.

Specifications

Specification Status Comment
HTML Living Standard
Определение ‘HTMLSelectElement’ в этой спецификации.
Живой стандарт Since the latest snapshot, HTML5, it adds the autocomplete property and the reportValidity() method.
HTML5
Определение ‘HTMLSelectElement’ в этой спецификации.
Рекомендация Is a snapshot of HTML Living Standard. It adds the autofocus , form , required , labels , selectedOptions , willValidate , validity and validationMessage properties. The tabindex property and the blur() and focus() methods have been moved to HTMLElement . The methods item() , namedItem() , checkValidity() and setCustomValidity() .
Document Object Model (DOM) Level 2 HTML Specification
Определение ‘HTMLSelectElement’ в этой спецификации.
Устаревшая options now returns an HTMLOptionsCollection (en-US). length now returns an unsigned long .
Document Object Model (DOM) Level 1 Specification
Определение ‘HTMLSelectElement’ в этой спецификации.
Устаревшая Initial definition.

Browser compatibility

BCD tables only load in the browser

See also

Found a content problem with this page?

This page was last modified on 21 июн. 2023 г. by MDN contributors.

Your blueprint for a better internet.

Источник

Читайте также:  Programming in python mark summerfield
Оцените статью