DOM - Selection of Node Element (querySelector)


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:


// 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 (with javascript and css example)

elements by selector

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

Example: from text to number, replacing text number in a list by digit

  • 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