DOM - Selection of Node Element

> (World Wide) Web - (W3|WWW) > The Document Object Model W3C API Interface (DOM)

1 - About

Selection of a node element in the DOM tree

Advertising

3 - Selection of

3.1 - 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>

Advertising

3.2 - one element by Id

3.2..1 - WebAPI

var id = "map"
var cssSelector = "#"+id;
var element;
 
// Web Api
element = document.getElementById(id);
// or Web Api Selector
element = document.querySelector(cssSelector);
// or Jquery
//element = $(cssSelector);
 
if(element.innerHTML != "")
	element.innerHTML= "The map id contain: " + element.innerHTML;
else
	element.innerHTML= "The map id contain nothing";
<div id="map" >div and div</div>

3.2..2 - window shortcut
  • window lets you select the id directly.

<h1 id="id1">H1 Content</h1>
console.log(window.id1.innerHTML);

3.3 - elements by selector

var divs = document.querySelectorAll('Selector');
Advertising
web/dom/select.txt ยท Last modified: 2019/02/16 17:40 by gerardnico