innerHTML and insertAdjacentHTML
Learn to change content with innerHTML and add at a position with insertAdjacentHTML.
Content with innerHTML
To read or change the HTML inside an element as a string, you use the innerHTML property. When you assign to it, the browser parses the string as HTML.
const box = document.querySelector('.box');
box.innerHTML = '<strong>Hello</strong>';This property is powerful, but if you put user text directly, a security hole appears. For untrusted data, prefer textContent.
Positioned insertion with insertAdjacentHTML
The insertAdjacentHTML method adds an HTML string at one of four positions relative to an element. The position names are: 'beforebegin' before the element, 'afterbegin' at the start inside, 'beforeend' at the end inside, 'afterend' after the element.
const list = document.querySelector('ul');
list.insertAdjacentHTML('beforeend', '<li>New</li>');It does not change the existing content; it adds next to it. Like innerHTML, it parses HTML; do not use it for untrusted data.
Exercise Append an HTML string to the list
The list variable points to a <ul> element. Use the insertAdjacentHTML method to add the string '<li>New item</li>' at the 'beforeend' position.
Show example solution
list.insertAdjacentHTML('beforeend', '<li>New item</li>');
Test yourself
-
Which places a <p> inside box?
const box = document.querySelector('.box'); // A box.textContent = '<p>Merhaba</p>'; // B box.innerHTML = '<p>Merhaba</p>'; // C box.setAttribute('p', 'Merhaba'); // D box.classList.add('p');- A
- B
- C
- D
Show answer
B — Correct! innerHTML parses the string as HTML.
-
Change content as HTML
const box = document.querySelector('.box'); box.____ = '<em>vurgu</em>';Show answer
const box = document.querySelector('.box'); box.innerHTML = '<em>vurgu</em>'; -
Match positions
- beforebegin
- Before the element
- afterbegin
- At the start inside
- beforeend
- At the end inside
- afterend
- After the element