How to clone element with given class name

前端 未结 4 1931
慢半拍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<elems.length; i++ ) {
        printHTML( elems[i].cloneNode(true) );
    }
    
    0 讨论(0)
  • 2020-12-07 04:24

    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));
    
    0 讨论(0)
  • 2020-12-07 04:29

    This does not work? :

    printHTML( document.getElementsByClassName("class_name")[0].cloneNode(true));
    
    0 讨论(0)
  • 2020-12-07 04:34

    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));
    } 
    
    0 讨论(0)
提交回复
热议问题