You can change the text or HTML of any element you’ve selected. To do so, you use two methods:
innerHTMLtextContent
textContent
textContent lets you change the text of an Element.
const element = document.querySelector('div')element.textContent = 'Hello world!'The DOM updates automatically when you change textContent.
innerHTML
innerHTML lets you change the HTML inside an element.
const element = document.querySelector('div')element.innerHTML = '<p class="red">The quick brown fox ...</p>'You can create complicated HTML that spans multiple lines with the help of template literals.
const element = document.querySelector('div')element.innerHTML = `<ol> <li>Pizza</li> <li>Bread</li> <li>Onion</li> <li>Broccoli</li> </ol>`
textContent vs innerHTML
If you want to change text, always use textContent because textContent is faster than innerHTML.
If you want to change the HTML inside an element, use innerHTML.
Exercise
Try the following:
- Change an element’s text with
textContent - Change an element’s inner HTML with
innerHTML
Change an element’s text with textContent
const element = document.querySelector('.element')element.textContent = 'New text!'Change an element’s inner HTML with innerHTML
const element = document.querySelector('.element')element.innerHTML = '<strong>Bold text!</strong>'Welcome! Unfortunately, you don’t have access to this lesson. To get access, please purchase the course or enroll in Magical Dev School.
Unlock this lesson