About
This page shows you how to select node elemenst in the DOM tree
If you want to select
the first element found
This section shows you how to returns the first element within the document of a selection.
In the below code:
The below example demonstrates:
- the webApi querySelect
- and the JQuery function selection
Demo:
- We add the dependency with the script element.
<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js"></script>
- The HTML where we will select the p element
<p>A p element to select</p>
- querySelector: With the DOM Web Api function querySelector select and returns the first element (in our case a object that has the HTMLParagraphElement prototype)
// Return the element selected
webApiElement = document.querySelector('body>p');
console.log("querySelector found the element "+webApiElement.__proto__.toString()+" with the text value ("+webApiElement.innerText+")");
// JQuery returns always a list of object, we need then to get the first one
jQueryElement = $('body>p:nth-of-type(1)')[0];
// same as element = JQuery(selector);
console.log("JQuery found the element "+jQueryElement+" with the text value ("+jQueryElement.innerText+")");
- The below code check that they are the same element
if (webApiElement == jQueryElement) {
console.log("The webAPIElement and the jQueryElement are the same")
}
- The above demo code outputs:
an element by its Id
You can also select only one element with the id attribute.
For more information, documentation and example, see the dedicated page: DOM - Select an element by its id (with javascript and css example)
multiple elements with a CSS selector
Example: from text to number, replacing text number in a list by digit
- A unordered list of number written in words.
<ul>
<li>One</li>
<li>Two</li>
<li>Three</li>
<li>Four</li>
</ul>
- With the querySelectorAll, we can select all li elements and transform the words in digit.
let mapping = { "One":1,"Two":2, "Three":3, "Four": 4 };
document.querySelectorAll('li').forEach(element => {
element.innerText = mapping[element.innerText];
});
- Result:
The querySelectorAll Web API function will:
- select node elements
- with a selctor as argument
- and returns a node list.
let divs = document.querySelectorAll('Selector');