DOM Manipulation

Modifying HTML with Javascript.

Here's some HTML

<h1>Page title</h1>
<div id="content">
  <p>Welcome to my page!</p>
</div>

Let's say you use document.querySelector() to get the element with id content.

var content = document.querySelector('#content')

The content variable contains an HTMLElement.

https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement

Add child element

To add a child element, first we create one.

https://developer.mozilla.org/en-US/docs/Web/API/Document/createElement

var child = document.createElement('p')

Add some text content.

https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/innerText

child.innerText = 'This is the child content'

Append the child element to content.

content.appendChild(child)

Level
Topics