DEV Community

Sam Thorogood for Google Web Dev

Posted on Edited on Originally published at whistlr.info

Beyond appendChild: Better convenience methods for HTML

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',
});
πŸ”₯ Jadwal & Hasil: chromiumdev/beyond appendchild better convenience methods for html n - Pertandingan Hari Ini πŸ”₯ Jadwal & Hasil: chromiumdev/beyond appendchild better convenience methods for html n - Pertandingan Hari Ini

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)
πŸ”₯ Jadwal & Hasil: chromiumdev/beyond appendchild better convenience methods for html n - Pertandingan Hari Ini πŸ”₯ Jadwal & Hasil: chromiumdev/beyond appendchild better convenience methods for html n - Pertandingan Hari Ini

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!');
πŸ”₯ Jadwal & Hasil: chromiumdev/beyond appendchild better convenience methods for html n - Pertandingan Hari Ini πŸ”₯ Jadwal & Hasil: chromiumdev/beyond appendchild better convenience methods for html n - Pertandingan Hari Ini

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!`);
πŸ”₯ Jadwal & Hasil: chromiumdev/beyond appendchild better convenience methods for html n - Pertandingan Hari Ini πŸ”₯ Jadwal & Hasil: chromiumdev/beyond appendchild better convenience methods for html n - Pertandingan Hari Ini

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);
πŸ”₯ Jadwal & Hasil: chromiumdev/beyond appendchild better convenience methods for html n - Pertandingan Hari Ini πŸ”₯ Jadwal & Hasil: chromiumdev/beyond appendchild better convenience methods for html n - Pertandingan Hari Ini

⚠️ 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 🀷
πŸ”₯ Jadwal & Hasil: chromiumdev/beyond appendchild better convenience methods for html n - Pertandingan Hari Ini πŸ”₯ Jadwal & Hasil: chromiumdev/beyond appendchild better convenience methods for html n - Pertandingan Hari Ini

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">
πŸ”₯ Jadwal & Hasil: chromiumdev/beyond appendchild better convenience methods for html n - Pertandingan Hari Ini πŸ”₯ Jadwal & Hasil: chromiumdev/beyond appendchild better convenience methods for html n - Pertandingan Hari Ini

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 πŸ‘‹

Top comments (14)

πŸ”₯ Jadwal & Hasil: chromiumdev/beyond appendchild better convenience methods for html n - Pertandingan Hari Ini
 
nickytonline profile image
Nick Taylor •

It never occurred to me to create new elements with object assign. πŸ”₯ I always created the element then added properties and attributes after.

πŸ”₯ Jadwal & Hasil: chromiumdev/beyond appendchild better convenience methods for html n - Pertandingan Hari Ini
 
samthor profile image
Sam Thorogood Google Web Dev •

I nearly didn't include this oneβ€”it was added last. But I've seen a few people remark on how neat it is in some of my codebases, so I'm glad to share? 🀷

πŸ”₯ Jadwal & Hasil: chromiumdev/beyond appendchild better convenience methods for html n - Pertandingan Hari Ini
 
maxart2501 profile image
Massimo Artizzu •

It's so useful when adding a bunch of properties to .style πŸ™‚

Object.assign(el.style, {
 left: x + 'px',
 top: y + 'px'
});
πŸ”₯ Jadwal & Hasil: chromiumdev/beyond appendchild better convenience methods for html n - Pertandingan Hari Ini Thread
 
nickytonline profile image
Nick Taylor • • Edited

I made a little helper function based on your example @samthor which also handles inline styles. Thought I'd share here in case anyone else finds it useful. So the only thing else I added was handling inline style and wrapped it all into a function.

πŸ”₯ Jadwal & Hasil: chromiumdev/beyond appendchild better convenience methods for html n - Pertandingan Hari Ini
 
jonathanburnhill profile image
Jonathan Burnhill •

I keep coming back to this because I love it and am using the object assign right now, I have a little question.

Is there a way in object assign to insert children such as for instance if I want to put a x next to a image to say delete?

πŸ”₯ Jadwal & Hasil: chromiumdev/beyond appendchild better convenience methods for html n - Pertandingan Hari Ini
 
samthor profile image
Sam Thorogood Google Web Dev •

I don't think so, sorry. You can't assign to .children in this way.

πŸ”₯ Jadwal & Hasil: chromiumdev/beyond appendchild better convenience methods for html n - Pertandingan Hari Ini
 
jonathanburnhill profile image
Jonathan Burnhill •

Thanks for your reply, I was playing with it a little bit probably when I should have been concentrating on work πŸ˜‚.
You can use innerHTML though!! And I called the on click with a function so learned 2 new things yesterday about it

πŸ”₯ Jadwal & Hasil: chromiumdev/beyond appendchild better convenience methods for html n - Pertandingan Hari Ini
 
yansusanto profile image
Yan Susanto •

Hi Sam,

For some reasons I stumbled upon your article while googling and if I may ask, how would you write vanilla JS for this

    $(".accordion-title").prepend(
        '<span class="toggle"><span></span><span></span></span>'
    );

Your input is much appreciated ;)

πŸ”₯ Jadwal & Hasil: chromiumdev/beyond appendchild better convenience methods for html n - Pertandingan Hari Ini
 
samthor profile image
Sam Thorogood Google Web Dev • • Edited

For a one-liner... hmm:

document.querySelector('.accordion-title').prepend(
  Object.assign(document.createElement('span'), {className: 'toggle', innerHTML: '<span></span><span></span>'}),
);

If you're not happy using innerHTML then it could look like this:

const toggleEl = Object.assign(document.createElement('span'), {class: 'toggle'});
toggleEl.append(document.createElement('span'), document.createElement('span'));
document.querySelector('.accordion-title').prepend(toggleEl);
πŸ”₯ Jadwal & Hasil: chromiumdev/beyond appendchild better convenience methods for html n - Pertandingan Hari Ini
 
maxart2501 profile image
Massimo Artizzu •

As a curiosity: .remove on <select> elements can take an optional argument. Why?

Because it's the method used to remove an option from its list. So, in this specific case, .remove does two different things: when called with no parameters, removes the element itself; when a index is passed, it removes the corresponding option in the list.

I'd suggest the awkwardly-specified, but still quite useful methods .insertAdjacentElement/.insertAdjacentHTML/.insertAdjacentText, that originated with Internet Explorer 4 (!), and take two arguments. The first of which is a string among 'beforebegin', 'beforeend', 'afterbegin' and 'afterend'. Weird.

But anyway, while the other two can be nicely polyfilled with other methods, .insertAdjacentHTML is quite unique, and can be seen as the only correct way to append a piece of HTML to an element without too much fuss or making a mess (someone said el.innerHTML += '<b>Just kidding!</b>'?).

πŸ”₯ Jadwal & Hasil: chromiumdev/beyond appendchild better convenience methods for html n - Pertandingan Hari Ini
 
samthor profile image
Sam Thorogood Google Web Dev •

I've not really used the .insertAdjacent... methods. Good point about adding HTML thoughβ€”I suppose the other way to do that is to create a dummy node (or fragment) and then append the content of that, but that is nice... if you're adding HTML directly.

πŸ”₯ Jadwal & Hasil: chromiumdev/beyond appendchild better convenience methods for html n - Pertandingan Hari Ini
 
dance2die profile image
Sung M. Kim •

Object.assign works wonderfully~~~

demo

πŸ”₯ Jadwal & Hasil: chromiumdev/beyond appendchild better convenience methods for html n - Pertandingan Hari Ini
 
kienngo profile image
ken •

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

This is sooooo gooood!!!

πŸ”₯ Jadwal & Hasil: chromiumdev/beyond appendchild better convenience methods for html n - Pertandingan Hari Ini
 
jonathanburnhill profile image
Jonathan Burnhill •

I love this and will be playing with it today!!