Understanding the DOMLesson 1.3
Reading and writing element properties in the DOM
textContent, innerHTML, innerText, value, setAttribute, getAttribute, dataset, classList
Reading and Writing Element Properties
Once you have a reference to an element, you can read or overwrite its content and attributes directly through properties.
Content Properties
const p = document.querySelector('p');
console.log(p.textContent); // raw text, no tags
p.textContent = 'Updated!'; // safe — escapes HTML
p.innerHTML = '<strong>Bold text</strong>'; // parses HTML
// Warning: never set innerHTML with untrusted user inputAttributes
const img = document.querySelector('img');
img.setAttribute('alt', 'A sunset photo');
console.log(img.getAttribute('src'));
// data-* attributes live in dataset
// <button data-user-id="42">
const btn = document.querySelector('button');
console.log(btn.dataset.userId); // "42"Form Inputs
For <input> and <textarea>, use the value property — not textContent.
const input = document.querySelector('#username');
console.log(input.value); // current field value
input.value = 'alice'; // sets the fieldUse textContent when inserting plain text. Reserve innerHTML for trusted HTML strings only.
