Selector API - ID (Unique Identifier) attribute

> (World Wide) Web - (W3|WWW) > Selector API

1 - About

The ID selectors 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.

Advertising

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

4 - CSS

4.1 - 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 */

4.2 - 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 */

Advertising

4.3 - 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}

5 - Javascript

  • window lets you select the id directly.

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

web/selector/id.txt · Last modified: 2019/02/16 17:40 by gerardnico