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:

  • a hash mark.
  • and the id name
/* 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

  • The HTML
<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>
  • The CSS
#TheId { color:blue; } /* The two p elements with the same ID will be blue, not only the first one */
  • The result, the two elements are blue:

Tag and ID selector

  • The HTML
<p id="TheId">A p element with the id "TheId"</p>
<div id="TheId">A div element with the id "TheId"</div>
  • The CSS with a tag selector and an Id selector (This is an AND logical predicate and it's called an intersection in the selector API)
p#TheId { color:blue; } /* Only the P element with the id attribute TheId will be blue */

With Descendant selector to animate a menu

  • The HTML
<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>
  • The CSS
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:

  • 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: