JavaScript追加带元素的字符串

时间:2014-06-27 18:26:06

标签: javascript html appendchild selectors-api

我试图使用越来越多的本机Javascript代码而不是jQuery。如果我想用jQuery将带有html元素的字符串附加到另一个分类元素中,那很容易:

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

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

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

FIDDLE

如何使用原生JavaScript中的短代码(不使用循环)?

我尝试了很多,例如我的想法:

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

可能先创建元素:

var svg = document.createElement(&#34; svg&#34;);

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

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

1 个答案:

答案 0 :(得分:0)

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

现在保存以供日后使用:

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

但不要that

请改为:

var appendToNodeList = function (nodelist, child) {
    Array.prototype.forEach.call(nodelist, function (parent) {
        parent.appendChild(child);
    }); 
};

appendToNodeList(document.querySelectorAll(".destination"), svg);
相关问题