Working With Attributes

Grade 11, page 6 of 10. A one-minute read.

HTML attributes (like src, href, alt, id and class) can also be read and changed:

JavaScript
const photo = document.querySelector("#photo");
const link = document.querySelector("#link");

// common attributes are available as properties
photo.src = "https://placehold.co/300x150?text=New+Photo";
photo.alt = "A brand new photo";
link.href = "https://javascript.info";
link.textContent = "Learn even more";

// or use the general-purpose methods
link.setAttribute("target", "_blank"); // open in a new tab
console.log(link.getAttribute("href"));

Form elements have their own useful properties, which you'll use a lot in Grade 12:

PropertyWhat it is
input.valueThe text currently typed in a text box
checkbox.checkedtrue if a checkbox is ticked
button.disabledSet to true to grey out a button so it can't be clicked

Custom data attributes

You can store your own extra information on elements using attributes that start with data-. JavaScript reads them through the dataset property (with the name turned into camelCase):

HTML
<button id="buy" data-product-id="42" data-price="150">Buy now</button>
JavaScript
const button = document.querySelector("#buy");
console.log(button.dataset.productId); // "42"  (always a string!)
console.log(button.dataset.price);     // "150"

This is a handy way to attach information to elements, like which product a "Buy" button belongs to.

Reading is step one

CurlyScript turns these notes into a game: short questions, an explanation after every answer, and a test at the end of each grade. Free, with nothing to sign up for.

Start learning