Unit 7 ยท JavaScript

7.8.2Manipulating elements and styles

JavaScript
const t = document.getElementById('title');

// Change content
t.textContent = 'New text';           // plain text (safe)
t.innerHTML = '<em>Styled</em> text'; // parses HTML (never use with untrusted user input: XSS risk)

// Change attributes
const img = document.querySelector('img');
img.src = 'images/new.png';
img.setAttribute('alt', 'New picture');
img.getAttribute('alt');
img.removeAttribute('width');

// Change CSS directly (property names in camelCase)
t.style.color = 'red';
t.style.backgroundColor = '#eee';
t.style.display = 'none';              // hide

// Better: switch CSS classes
t.classList.add('highlight');
t.classList.remove('highlight');
t.classList.toggle('highlight');       // add if absent, remove if present
t.classList.contains('highlight');     // true or false

// Create, add and remove elements
const li = document.createElement('li');
li.textContent = 'Three';
document.querySelector('ul').appendChild(li);        // add at the end
document.querySelector('ul').prepend(li);            // add at the start
li.remove();                                         // delete it

Pattern: build a list from an array

JavaScript
const fruits = ['Mango', 'Apple', 'Banana'];
const list = document.getElementById('fruitList');
list.innerHTML = '';                        // clear
fruits.forEach(f => {
  const li = document.createElement('li');
  li.textContent = f;
  list.appendChild(li);
});