DEV Community

Discussion on: Beyond appendChild: Better convenience methods for HTML

Collapse
 
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 ;)

Collapse
 
samthor profile image
Sam Thorogood • 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);