3 ms·
My new favorite bit of vanilla JavaScript has been around since Chrome 1.0 and IE: Element.insertAdjacentHTML. To say it's useful is an understatement, especial
by russellbeattie 3y ago
My new favorite bit of vanilla JavaScript has been around since Chrome 1.0 and IE: Element.insertAdjacentHTML. To say it's useful is an understatement, especially with multi-line Strings using `. I can't believe it's been around so long and I only realized it a year or so ago.
The insertAdjacentHTML(position, text) method of the Element interface parses the specified text as HTML or XML and inserts the resulting nodes into the DOM tree at a specified position.
A contrived example of something that's a pain to do with raw DOM:
let anchors = ['#a', '#b', '#c'];
let el = document.querySelector('ul');
for (let a of anchors) {
el.insertAdjacentHTML(
'beforeend',
`<li><a href="${a}">${a.substr(1)}</a></li>`
);
}
Previously I would have to create the li element, then the a element, add it as a child, set the href attribute, then the text value of the a element, then insert it into the ul element. Or, I'd batch it all up as a big string and insert it using innerHTML. Modifying an existing list was even more painful and verbose.
1. https://developer.mozilla.org/en-US/docs/Web/API/Element/insertAdjacentHTML https://developer.mozilla.org/en-US/docs/Web/API/Element/ins...