How to clone element with given class name

前端 未结 4 1936
慢半拍i
慢半拍i 2020-12-07 03:36

I am using getElementById when I need to clone the div element.

Code:

printHTML( document.getElementById(\"div_name\").cloneNode(true));         


        
4条回答
  •  借酒劲吻你
    2020-12-07 04:19

    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

提交回复
热议问题