Editing the DOM

You can also modify the DOM. This allows you to create 'interactive websites' which change as your user does things.

To do this we first need to grab the HTMLElement we want to edit from the DOM using document.querySelector('selector')

htmlElement.textContent

HTMLElement has a key textContent which you can assign to change the text inside an HTML element.

If the DOM has the following HTML:

<p class="red">b</p>
const htmlElement = document.querySelector('p') // a HTMLElement: <p class="red">b</p>
htmlElement.textContent = 'c'

// the HTML in the DOM now looks like: <p class="red">c</p>

htmlElement.style.cssText

HTMLElement has a key style.cssText which you can assign to change the css style of the element.

If the DOM has the following HTML:

<p>b</p>
const htmlElement = document.querySelector('p') // a HTMLElement: <p class="red">b</p>
htmlElement.style.cssText = 'color: blue;'

// <p style="color: blue;">b</p> is now in the DOM

Adding new HTML elements to the DOM

Creating new HTMLElement

To create a new DOM element:

const pTag = document.createElement("p") // creates a new <p></p>

const divTag = document.createElement("div") // creates a new <div></div>

Adding new HTMLElements to the DOM

We can add new elements to the DOM using document.createElement( and htmlElement.appendChild(anotherHtmlElement)

If the DOM has the following HTML:

<div id="container">
</div>
const pTag = document.createElement("p") // creates a new <p></p>

pTag.textContent = 'Hello World' // pTag is now: <p>Hello World</p>

document.querySelector('#container').appendChild(pTag)

// Dom is now:
// <div id="container">
//   <p>Hello World</p>
// </div>