This page shows you how to select node elemenst in the DOM tree
This section shows you how to returns the first element within the document of a selection.
In the below code:
The below example demonstrates:
Demo:
<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js"></script>
<p>A p element to select</p>
// 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+")");
if (webApiElement == jQueryElement) {
console.log("The webAPIElement and the jQueryElement are the same")
}
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)
Example: from text to number, replacing text number in a list by digit
<ul>
<li>One</li>
<li>Two</li>
<li>Three</li>
<li>Four</li>
</ul>
let mapping = { "One":1,"Two":2, "Three":3, "Four": 4 };
document.querySelectorAll('li').forEach(element => {
element.innerText = mapping[element.innerText];
});
The querySelectorAll Web API function will:
let divs = document.querySelectorAll('Selector');