Manipulação do DOM
Árvore DOM
Fonte: Google Developers - Constructing the Object Model
Element
Element.innerHTML
document.body.innerHTML = '<h1>Lorem ipsum</h1>';
document.body.innerHTML = '<h1>Lorem ipsum</h1>';
Element.innerText
const p = document.querySelector('p');
p.innerText = 'Lorem ipsum';
const p = document.querySelector('p');
p.innerText = 'Lorem ipsum';
Element.classList
document.body.classList.remove('color-red');
document.body.classList.add('color-blue');
document.body.classList.remove('color-red');
document.body.classList.add('color-blue');
Element.className
document.body.className = 'text-center';
document.body.className = 'text-center';
Element.setAttribute()
document.body.setAttribute('class', 'active red');
document.body.setAttribute('class', 'active red');
HTMLElement
HTMLElement.style
const p = document.querySelector('p');
p.style.cssText = 'color: blue;';
const p = document.querySelector('p');
p.style.cssText = 'color: blue;';
const p = document.querySelector('p');
p.style.cssText = 'color: blue; font-size: 1.1rem;';
const p = document.querySelector('p');
p.style.cssText = 'color: blue; font-size: 1.1rem;';
const p = document.querySelector('p');
p.style.fontSize = '1.1rem';
const p = document.querySelector('p');
p.style.fontSize = '1.1rem';
Element.setAttribute() (Alternative):
const p = document.querySelector('p');
p.setAttribute('style', 'color: blue; font-size: 1.1rem;');
const p = document.querySelector('p');
p.setAttribute('style', 'color: blue; font-size: 1.1rem;');
const p = document.querySelector('p');
p.setAttribute('class', 'active red');
const p = document.querySelector('p');
p.setAttribute('class', 'active red');
Element.classList (Alternative):
const p = document.querySelector('p');
p.classList.add('color-blue');
const p = document.querySelector('p');
p.classList.add('color-blue');
Element.className (Alternative):
const p = document.querySelector('p');
p.className = 'text-center';
const p = document.querySelector('p');
p.className = 'text-center';
HTMLInputElement
HTMLInputElement.value
const input = document.querySelector('#name');
console.log(input.value);
input.value = 'Alice';
console.log(input.value);
const input = document.querySelector('#name');
console.log(input.value);
input.value = 'Alice';
console.log(input.value);
HTMLInputElement.checked
const input = document.querySelector('#male');
input.checked;
const input = document.querySelector('#male');
input.checked;