← Back to JavaScript, page 4

javascript-0065 · Easy fresher

How do you select and update elements in the DOM, and what is the difference between textContent and innerHTML?

querySelector and querySelectorAll select elements by CSS selector, while getElementById is the fast lookup by id. textContent sets plain text and is safe, whereas innerHTML parses a string as HTML and is dangerous with untrusted input. createElement with append builds nodes without parsing, and classList, dataset, and setAttribute update classes, data values, and attributes.

Full answer

The Document Object Model (DOM) is the live tree of objects the browser builds from HTML. JavaScript reads and changes the page by changing that tree.

To select: document.querySelector(selector) returns the first match or null, querySelectorAll returns a static NodeList of every match, and getElementById finds one element by id. getElementsByClassName returns a live HTMLCollection that updates when the page changes, which can surprise a loop. A NodeList from querySelectorAll supports forEach, and spread turns it into a real array.

To update, there are several properties. textContent sets or reads plain text, and any markup in the string is shown as text. innerHTML parses the string as HTML, so it can build structure quickly, but placing untrusted text in it allows cross-site scripting. innerText depends on rendering and is slower. For structure without parsing, document.createElement, then set properties, then append to a parent. element.remove() deletes an element.

Classes change with classList.add, remove, toggle, and contains. Data attributes read through dataset: data-user-id becomes dataset.userId. Other attributes use getAttribute, setAttribute, and removeAttribute. Form values use the value property.

Reading the DOM and writing to it repeatedly can be slow. Building a DocumentFragment or a single string and inserting once reduces repaints. If the selector finds nothing, querySelector returns null, so check before using the result.

javascript
document.body.innerHTML = `
  <ul id="courses">
    <li class="course" data-level="easy">HTML</li>
    <li class="course" data-level="hard">JavaScript</li>
  </ul>
  <p id="note"></p>`;

const list = document.querySelector('#courses');
const first = document.querySelector('.course');
const all = document.querySelectorAll('.course');
console.log(first.textContent, all.length, document.querySelector('.missing'));
console.log([...all].map((li) => li.dataset.level));

const live = document.getElementsByClassName('course');
const staticList = document.querySelectorAll('.course');
const extra = document.createElement('li');
extra.className = 'course';
extra.textContent = 'CSS';
list.append(extra);
console.log('live collection:', live.length, 'static list:', staticList.length);

extra.classList.add('highlight');
extra.classList.toggle('highlight');
extra.classList.toggle('done', true);
extra.dataset.level = 'medium';
extra.setAttribute('title', 'Styling');
console.log(extra.outerHTML);

const note = document.getElementById('note');
const userInput = '<img src=x onerror="alert(1)">';
note.textContent = userInput;
console.log(note.innerHTML);
console.log('children created from textContent:', note.children.length);
note.innerHTML = userInput;
console.log('children created from innerHTML:', note.children.length);

const fragment = document.createDocumentFragment();
for (const name of ['React', 'Node']) {
  const li = document.createElement('li');
  li.textContent = name;
  fragment.append(li);
}
list.append(fragment);
console.log([...list.children].map((li) => li.textContent));

first.remove();
console.log(list.children.length);

Written for a browser console or script tag; checked here with Node.js v24.22.1 and jsdom, two runs with identical output. Output: HTML 2 null [ 'easy', 'hard' ] live collection: 3 static list: 2 <li class="course done" data-level="medium" title="Styling">CSS</li> &lt;img src=x onerror="alert(1)"&gt; children created from textContent: 0 children created from innerHTML: 1 [ 'HTML', 'JavaScript', 'CSS', 'React', 'Node' ] 4

Key points

  • querySelector gives the first match or null; querySelectorAll gives a static NodeList.
  • getElementsByClassName gives a live HTMLCollection.
  • textContent treats text as text; innerHTML parses HTML and is unsafe with untrusted input.
  • createElement plus append builds nodes without parsing.
  • classList, dataset, and setAttribute update classes, data, and attributes.

Common mistakes

  • Using innerHTML with user-provided text.
  • Using the result of querySelector without checking for null.
  • Looping over a live HTMLCollection while adding or removing elements in the loop.
  • Reading and writing layout properties alternately in a loop, which forces repeated layout.

Follow-ups

  • What is the difference between a NodeList and an HTMLCollection?
  • When would you use insertAdjacentHTML or the Sanitizer API?
  • How does event delegation reduce the need to select every element?

Tips

  • Contrast textContent and innerHTML in terms of security first; that is the usual follow-up.
  • Mention live versus static collections; most candidates do not.
  • Use createElement and append for dynamic content and explain why it is safer.