0

我正在尝试使用越来越多的原生 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);

小提琴

如何使用本机 JavaScript 中的短代码(不使用循环)来做到这一点?

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

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

也许首先创建元素:

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

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

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

1 回答 1

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

但不要那样

改为这样做:

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

appendToNodeList(document.querySelectorAll(".destination"), svg);
于 2014-06-27T23:37:38.697 回答