DOM - Selection of Node Element

About

Selection of a node element in the DOM tree

Selection of

the first element by selector

Returns the first element within the document of a selection.

In the below code:

Example:

// Return the element selected
webApiElement = document.querySelector('body>p');
console.log("querySelector found the element "+webApiElement.__proto__.toString());
// 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);
  • And they are the same element
if (webApiElement == jQueryElement) {
  console.log("The webAPIElement and the jQueryElement are the same")
}
<p>A p element to select</p>

one element by 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

elements by selector

var divs = document.querySelectorAll('Selector');

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>
  • 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:

Powered by ComboStrap