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>`
innerHTML and the DOM will update. 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