How to clone element with given class name

六眼飞鱼酱① 提交于 2019-11-28 02:05:30

getElementsByClassName gets a nodelist, or an array-like object containing elements if you will, as there can be more than one element with the same class.

getElementsByClassName does this even if only one element matches the class.
You can generally recognize methods like that be the s in getElements, which means it gets multiple elements, i.e. a nodeList.

getElementById only gets one element as ID's are unique.

To get the first element in the nodelist, use bracket notation, like so:

document.getElementsByClassName("div_name")[0].cloneNode(true);

or one could use querySelector, which gets the first matching element only

document.querySelector(".div_name").cloneNode(true);

The jQuery solution would be:

$('.div_name').clone(true);

and to iterate over elements with a certain classname you'd use a loop

var elems = document.getElementsByClassName("div_name");

for ( var i=0; i<elems.length; i++ ) {
    printHTML( elems[i].cloneNode(true) );
}

Due to getElementsByClassName returns an object's array, so you have to use for loop to iterates among them, as follows:

 for (i = 0; i < document.getElementsByClassName("div_name").length; i++){  

printHTML( document.getElementsByClassName("div_name")[i].cloneNode(true));
}

otherwise, if you know the index of the element you have let we say 1

printHTML( document.getElementsByClassName("div_name")[1].cloneNode(true));

This does not work? :

printHTML( document.getElementsByClassName("class_name")[0].cloneNode(true));

You can loop through the elements and clone one by one...

var e = document.getElementsByClassName('div');
for (var i = 0; i < e.length; i += 1) {
    // Clone e[i] here
    console.log(e[i].cloneNode(true));
} 
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!