Search code examples
javascripthtmlprependcreateelement

Can I create a self-closing element with createElement?


I'm trying to append a line of HTML before all the children of the body.

Right now I have this:

// Prepend vsr-toggle
var vsrToggle = document.createElement("div");
vsrToggle.innerHTML = "<input type='checkbox' name='sr-toggle' id='srToggle'><label for='srToggle' role='switch'>Screen reader</label>"
document.body.insertBefore(vsrToggle, pageContent);

It's working fine because the HTML is being added to the created div. However, I need to prepend this element without wrapping it in a div.

Is there a way to prepend the HTML without first creating an element? If not, can I create the input as a self-closing element and append the label to it?

Is there a better way to achieve this?

Cheers!


Solution

  • Use document.createDocumentFragment() to create a node, that isn't automatically added to the document. You can then add elements to this fragment and finally add it to the document.

    This is a good link: Document fragment

    How to use:

    var fragment = document.createDocumentFragment();
    fragment.innerHTML = '<input />';
    document.body.appendChild(fragment);