Script Valley
JavaScript in the Browser: DOM, Events & APIs
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 input

Attributes

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 field

Use textContent when inserting plain text. Reserve innerHTML for trusted HTML strings only.

Up next

How to traverse the DOM tree with parent, child, and sibling properties

Sign in to track progress

Reading and writing element properties in the DOM โ€” Understanding the DOM โ€” JavaScript in the Browser: DOM, Events & APIs โ€” Script Valley โ€” Script Valley