Table of Contents

Selector API - ID (Unique Identifier) attribute

About

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 the elements matching the criteria.

Syntax

ID selector are composed of a:

/* Selects the first element with ID "header"  */
#header     
/* Selects element with ID "nav"  (ie for a navigation bar) */
#nav 

Demo

Two elements with the same ID

<p id="TheId">This one is the first element with the id "TheId"</p>
<p id="TheId">This one is the second element with the id "TheId"</p>
#TheId { color:blue; } /* The two p elements with the same ID will be blue, not only the first one */

Tag and ID selector

<p id="TheId">A p element with the id "TheId"</p>
<div id="TheId">A div element with the id "TheId"</div>
p#TheId { color:blue; } /* Only the P element with the id attribute TheId will be blue */

With Descendant selector to animate a menu

<ul id="HeaderMenu" > 
   <li><a href="category/obiee/" >OBIEE</a></li>
   <li><a href="category/owb/">OWB</a></li>
   <li><a href="category/datawarehouse/">DataWarehouse</a></li>
   <li><a href="category/oracle_database/">Oracle Database</a></li>
</ul>
ul#HeaderMenu 
{
  float:left;
  width:100%;
  padding:0;
  margin:0;
  list-style-type:none;
}
ul#HeaderMenu a
{
  float:left;
  width:auto;
  text-decoration:none;
  color:white;
  background-color:purple;
  padding:0.2em 0.6em;
  border-right:1px solid white;
}
ul#HeaderMenu a:hover {background-color:blue}
ul#HeaderMenu li {display:inline}

Javascript selection

The id selector can be used to select a specific element with the querySelector function of the dom document

Demo:

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}`);
<div id="box" >Box selected with a selector</div>