Search code examples
getelementsbyclassnameclonenode

getElementsByClassName is not working, but Id's work fine


I am trying to get some elements by Class Name and it's not working. However, if I change to get element by ID, it works fine. Would like to understand why Class Name method is not working. Here is a JSFiddle: http://jsfiddle.net/kXmpY/2681/ If I change to ID's it works. What am I missing?

HTML:

<a href="#" class="cloneLink">Click me</a>
<div class="duplicator"> 
<label for="newInput">Label</label>
<input type="text">
</div>

JS:

document.getElementsByClassName("cloneLink").onclick = duplicate;

var i = 0;
var original = document.getElementsByClassName("duplicator");

function duplicate() {
var clone = original.cloneNode(true); // "deep" clone
clone.id = "duplicator" + i++; // there can only be one element with 
an ID
original.parentNode.appendChild(clone);
}

Solution

  • document.getElementsByClassName returns a HTMLCollection instead of a single element.

    You need to write

    var original = document.getElementsByClassName("duplicator")[0];
    

    That is if you have a single element with that classname you want to manipulate.

    The getElementsByClassName() method returns an array-like object of all child elements which have all of the given class names.

    Read more about this here