Beyond appendChild: Better convenience methods for HTML

Sam Thorogood - Jun 9 '19 - - Dev Community

I've built on the web for a while now. So long that when I'm writing vanilla HTML/JS, my go-to has always been .appendChild() to add new HTML elements, and a huge series of createElement calls along with it.

But there's actually some lesser-known convenience methods that we can use now (well, in a post-IE11 world, where all devs should be). 🌎👍 I'm not arguing against your framework or components, but sometimes, you just have to write vanilla JS. 🍦

One-Line Element Creation

I confess 😅 that this isn't really one line, but it's one statement:

const el = Object.assign(document.createElement('div'), {
  textContent: `Your div now has text`,
  className: 'and-is-classy',
});
Enter fullscreen mode Exit fullscreen mode

The helper Object.assign wasn't available in IE11.

Remove Self

This one is pretty well-known.

const el = document.getElementById('something');
el.remove();   // instead of el.parentNode.removeChild(el)
Enter fullscreen mode Exit fullscreen mode

Insert Element or Text

The .append() method can append any real elements, or it will automatically create a text node if you pass it a string. It takes any number of arguments.

el.append(document.createElement('hr'), 'I get upgraded to a text node!');
Enter fullscreen mode Exit fullscreen mode

There's also .prepend() which is the opposite of .append(). It inserts all the elements, in-order, at the start of the element:

const heading = Object.assign(document.createElement('h2', {
  textContent: 'List Of Awesome HTML Methods',
});
list.prepend(heading, `You Won't Believe How Many We Found!`);
Enter fullscreen mode Exit fullscreen mode

Insert Relative To Element

Every element has methods .before() and .after(). These insert new HTML nodes directly adjacent to the current node. Like the methods above, they accept any number of other elements or strings.

myHeading.before(superHeading);
myHeading.after(`Here's a list of awesome stuff`, theList);
Enter fullscreen mode Exit fullscreen mode

⚠️ There's one caveat: in our example, if myHeading isn't actually on the page—it's a temporary element—these methods will just fail silently without throwing an Error.

Replace Self

Rather than doing a parentNode.replaceChild dance, we can now self-destruct an element and replace it with something new. Again, we can replace ourselves with any number of other elements or strings (even none!).

const fancyItem = Object.assign(document.createElement('strong'), {
  textContent: 'fancy',
});
someFancyHeading.replaceWith('Less', fancyItem, 'heading');
someFancyHeading.replaceWith();  // although you could just use .remove 🤷
Enter fullscreen mode Exit fullscreen mode

Class Force Set

If you want to set the state of a class to a variable true or false, you can pass a second param to .classList.toggle:

const someState = false;
theDiv.classList.toggle('foo', !someState);  // forces foo on
theDev.classList.toggle('bar', someState);   // forces bar off
// result e.g. <div id="theDiv" class="foo">
Enter fullscreen mode Exit fullscreen mode

This is probably well-known. But if you're explicitly not supporting IE11, it's nice to be confident that this now works. 🎉

Done!

What have I missed? Let me know if there any other old habits you've recently discovered you can let go of.

9 👋

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .