HTML attributes (like src, href, alt, id and class) can also be read and changed:
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:
| Property | What it is |
|---|---|
input.value | The text currently typed in a text box |
checkbox.checked | true if a checkbox is ticked |
button.disabled | Set 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):
<button id="buy" data-product-id="42" data-price="150">Buy now</button>
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.