liveBook · Manning

Id attribute

As explained in Web Components in Action

An HTML attribute that assigns an identifier to an element for document and selector-based addressing.

The id attribute assigns a unique identifier to an HTML element. Use it when addressing a page-wide element or fetching a template from a document-wide pool. section 7.4

Choose between IDs and classes according to the scope of the lookup:

  • Use an id when each identifier appears only once on the entire HTML page and document-wide selection is appropriate. section 7.4
  • Use a class when templates or internal elements belong to a component and should be queried within a specific container. section 7.4
  • When moving between Shadow DOM and regular DOM, replace getElementById and id selectors with querySelector and class selectors. section 12.1

Template lookup inside a component

A page-wide template might use <template id="default-card">. A component-scoped template instead uses <template class="default-card"> and is found with this.templates.querySelector('template.' + this.getAttribute('layout')). section 7.4

Listing 7.12. Contents of the populateCard function
populateCard() {                                    #1
   const template = this.templates.querySelector(
   'template.' + this.getAttribute('layout'));    #2
   if (template) {
       const clone =                                #3
               template.content.cloneNode(true);
       this.cardElement.innerHTML = '';             #4
       this.cardElement.appendChild(clone);         #5
   }
}

See the component-scoped querySelector call, template cloning, and insertion steps that replace document-wide ID lookup. section 7.4

How Web Components in Action covers it

How deep it goes
Explains uniqueness and selector replacement through template loading, stopping short of broader selector syntax.
Examples
Demonstrates default-card templates and slider elements migrated from id selectors such as bg-overlay and thumb to classes.
What you can do after
Apply it via DOM selectors by choosing document-wide IDs or component-scoped classes for template and element addressing.
How it connects
Connects IDs with HTML templates, the DOM, CSS classes, querySelector, Shadow DOM, and Web Components.

Also explained in

Compare how 2 books explain id attribute →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Web Components in Action. The section links point to the parts of the book it draws on.