DOM - Select an element by its id

About

This page shows you how to select an element via the id attribute

Demo

getElementById

The function getElementById of the document object permits to pass the id value in order to select the element

Example:

  • The Javascript
let id = "box"
let element = document.getElementById(id);
console.log(`The innerText of the element with the id ${id} is:  ${element.innerText}`);
  • The HTML
<div id="box" >Box selected with the id</div>
  • The result:

Selector

querySelector

The function querySelector of the document object permits to pass a selector value in order to select the first element selectioned.

The selector id syntax is:

#id

Example:

  • The javascript
let id = "box"
let selector = "#"+id;
let element = document.querySelector(selector);
console.log(`The innerText of the element with the id ${id} is:  ${element.innerText}`);
  • The HTML
<div id="box" >Box selected with a selector</div>
  • The result:

css

All CSS rules are based on selector.

Example:

  • The HTML
<p id="TheId">A blue paragraph</p>
#TheId { color:blue; } 
  • The result

window shortcut

The javascript window objects lets you select the element by id directly with the short notation

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

JQuery

The jquery function accepts a selector value and manipulate all element at once. If we use a id selector, we will manipulate only one element.

Example:

  • The javascript with the text() function
let id = "box"
let selector = "#"+id;
let element = $(selector);
console.log(`The innerText of the element with the id ${id} is:  ${element.text()}`);
  • The HTML
<div id="box" >Box selected with jquery</div>
  • The result:

Powered by ComboStrap