DOM - Select an element by its id (with javascript and css example)

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:





Discover More
Devtool Chrome Event Listener
DOM Event Handler - On Properties with Javascript (Interface Definition Language - IDL )

An IDL event handler is a way to define an event handler for one element via the on javascript properties known as the Interface Definition Language (IDL) (ie defined in the object interface, in the code)...
DOM - Selection of Node Element (querySelector)

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: selector is a selector...
Chrome Devtool Selector
Selector API - ID (Unique Identifier) attribute

The ID selector is a selector that match the elements with the given ID attribute Normally, an ID can be used only once each in a document but if it's not the case, the selectors will still return all...



Share this page:
Follow us:
Task Runner