DOM Manipulation

Exercise 0

Modifying HTML elements with JavaScript - note that the body of this page already includes empty HTML tags. See the page here.

HTML:

<p></p>
<h3></h3>
<div id="div1">
  <h1></h1>
  <p id="inner-p"></p>
</div>

JavaScript:

const p = document.querySelector('p');
p.style.color = 'red';
p.textContent = 'Hey I\'m red!'

const h3 = document.querySelector('h3');
h3.style.color = 'blue';
h3.textContent = 'I\'m a blue h3!'

const div = document.querySelector('#div1');
div.style.border = '1px solid black';
div.style.backgroundColor = 'pink';
//another method:
//div.setAttribute('style', 'border: 1px solid black; background-color: pink');
console.log(div);

const h1 = document.querySelector('h1');
h1.textContent = 'I\'m in a div';

const innerP = document.querySelector('#inner-p');
innerP.textContent = 'ME TOO!';

Creating new HTML elements with JavaScript

With this method, the body is empty and all of the HTML body elements are created with JavaScript. See the page here.

const firstP = document.createElement('p');
firstP.textContent = 'Hey I\'m red!';  
firstP.setAttribute('id', 'first-p');
document.body.appendChild(firstP);
//below is an example of getting the element after it's created
document.querySelector('#first-p').style.color = 'red';

const h3 = document.createElement('h3');
h3.innerHTML = 'I\'m a blue h3!'
h3.style.color = 'blue';
document.body.appendChild(h3);

const newdiv = document.createElement('div');
newdiv.style.border = '1px solid black';
newdiv.style.backgroundColor = 'pink';
newdiv.setAttribute('id', 'new-div');
//we need to append the new element to the body
document.body.appendChild(newdiv);

const h1 = document.createElement('h1');
h1.innerHTML = 'I\'m in a div';

const divP = document.createElement('p');
divP.innerHTML = 'ME TOO!';
//we need to append the new elements to the inside of the div we created earlier
document.getElementById("new-div").appendChild(h1);
document.getElementById("new-div").appendChild(divP);