Search code examples
javascripthtmlappendchildselectors-api

JavaScript append string with element(s)


I'm trying to use more and more native Javascript code in stead of jQuery. If I want to append a string with html elements in another classified elements with jQuery it's very easy:

<div class='destination'></div>
<div class='destination'></div>

var selector = "class='svg_element'";
var svgElement = "<svg " + selector + " ></svg>";

$(".destination").append(svgElement);

FIDDLE

How can I do this with short code in native JavaScript (without using a loop)?

I tried a lot, for example my simply thoughts:

document.querySelectorAll(".destination").appendChild(svgElement);

Maybe something with creating the element first:

var svg = document.createElement("svg");

//works
document.querySelector(".destination").appendChild(svg);

//doesn't works
document.querySelectorAll(".destination").appendChild(svg);

Solution

  • Array.prototype.forEach.call( document.querySelectorAll(".destination"),
        function (node) { node.appendChild(svg); }
    );  
    

    Now save it for later:

    NodeList.prototype.append = function (child) {
        Array.prototype.forEach.call(this, function (parent) {
            parent.appendChild(child);
        }); 
    };  
    

    But don't do that.

    Do this instead:

    var appendToNodeList = function (nodelist, child) {
        Array.prototype.forEach.call(nodelist, function (parent) {
            parent.appendChild(child);
        }); 
    };
    
    appendToNodeList(document.querySelectorAll(".destination"), svg);