Start learning free

LESSON 30 OF 161 · FRONTEND: JAVASCRIPT IN THE BROWSER

Read and Change Attributes in JavaScript

Practice

An HTML tag carries attributes: name and value pairs like src="mug.png", alt="…" or href="/products/1". They say which file an image shows, what a screen reader reads out, and where a link goes. Your script can read them and change them.

The common attributes are also properties of the element: assigning img.src or img.alt changes the attribute. setAttribute(name, value) works for any attribute. And an attribute whose name starts with data- is yours: the browser ignores it, and the script reads it in dataset, without the prefix. Its value is always a string.

// in the HTML: <a id="help" href="#" data-page="faq">Help</a>
const help = document.querySelector("#help");
console.log(help.dataset.page);                       // faq
help.setAttribute("href", "/" + help.dataset.page);   // the link goes to /faq

The lamp's card is <li class="card" id="lamp" data-id="3">. Its photo is still the placeholder coming-soon.png with no alt text, and its Details link goes to #. When the check opens the page, it must print:

> open the page
  console.log: app.js is running
  console.log: Mug
  console.log: Notebook
  console.log: Lamp
  console.log: The lamp card has data-id 3
  screen:
    …
        item
          heading 3: Lamp
          image: A brass desk lamp
          text: $29
          link: Details -> /products/3

Your task: at the end of app.js, find the lamp's card, log "The lamp card has data-id" and its data-id, give its photo the file lamp.png and the alt text "A brass desk lamp", and point its Details link to /products/ followed by the card's data-id.


Assignment
Follow the Coding Tutorial to find the lamp's card, read its data-id, and change its photo's src and alt and its link's href.


Hint
The page has three images and three links, so search inside the lamp's card: lamp.querySelector(…), not document.querySelector(…). The data-id attribute is read as dataset.id.


STEP 1 OF 7
    Ctrl + Enter to check

    Dom Attributes in JavaScript

    Keep going with JavaScript1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free