liveBook · Manning

Attribute

As explained in Secrets of the JavaScript Ninja, Second Edition

A named association on an object that holds a value or provides accessor behavior.

In the browser DOM, read or update an element attribute with getAttribute() and setAttribute(), or use a corresponding element property. For id, the two stay linked in the demonstrated tests, but linked values are not always identical, and not every attribute has a corresponding property. section 12.2

A separate JavaScript technique attaches an id property to a function to recognize callbacks already stored and avoid adding duplicates. This is property-based tracking, not DOM attribute access. section 3.2.1

Listing 12.5. Accessing attribute values via DOM methods and properties
<div></div>
<script>
  document.addEventListener("DOMContentLoaded", () => {
    const div = document.querySelector("div");                  #A
    div.setAttribute("id","ninja-1");                           #B
    assert(div.getAttribute('id') === "ninja-1",                #B
           "Attribute successfully changed");                   #B
    div.id = "ninja-2";                                         #C
    assert(div.id === "ninja-2",                                #C
           "Property successfully changed");                    #C
    
    assert(div.getAttribute('id') === "ninja-2",                #D
           "Attribute successfully changed via property");      #D
    div.setAttribute("id","ninja-3");                           #E
    assert(div.id === "ninja-3",
           "Property successfully changed via attribute");
    assert(div.getAttribute('id') === "ninja-3",
           "Attribute successfully changed");
  });
</script>

See how setting a div’s id through either the DOM method or the element property affects the other. section 12.2

How Secrets of the JavaScript Ninja, Second Edition covers it

How deep it goes
Compares attribute and property behavior through id examples, but stops short of explaining when linked values differ.
Examples
Demonstrates changing a div’s id and tagging a function to prevent duplicate callback storage.
What you can do after
Operate DOM elements by reading or updating id through DOM methods or its corresponding property.
How it connects
Links DOM attributes with element properties and separately connects function properties with callback storage.

Also explained in

Compare how 26 books explain attribute →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Secrets of the JavaScript Ninja, Second Edition. The section links point to the parts of the book it draws on.