Element Properties

Every element also has the properties.innerHTMLand.textContent(as well as.innerText, which is similar to.textContent, but has someimportant differences). These hold the HTML and plain text content respectively. They are writable properties, meaning we can modify elements and their contents directly:

// Replace the inner HTML
myElement.innerHTML = 
    <h2>New content</h2>
    <p>beep boop beep boop</p>

// Remove all child nodes
myElement.innerHTML = null

// Append to the inner HTML
myElement.innerHTML +=
  `<a href="foo.html">continue reading...</a>

Appending markup to the HTML as shown above is usually a bad idea though, as we’d lose any previously made property changes on the affected elements (unless we persisted those changes as HTML attributes as shown insection 2) and bound event listeners. Setting the.innerHTMLis good for completely throwing away markup and replacing it with something else, e.g. server-rendered markup. So appending elements would better be done like so:

const link = document.createElement('a')
const text = document.createTextNode('continue reading...')
const hr = document.createElement('hr')

link.href = 'foo.html'



With this approach however we’d cause two browser redraws — one for each appended element — whereas changing the.innerHTMLonly causes one. As a way around this performance issue we can first assemble all nodes in a DocumentFragment, and then just append that single fragment:

const fragment = document.createDocumentFragment()



results matching ""

    No results matching ""