getElementsByClassName
returns an HTMLCollection
(it used to be a NodeList
; let's just call it a list), not just one element, and that list doesn't have an innerHTML
property.
If you want to copy the elements with the class, you can do it in a loop wiht cloneNode
:
setTimeout(function() {
var element = document.getElementById("unique_ID");
element.innerHTML = "";
Array.prototype.forEach.call(document.querySelectorAll(".a_random_class"), function(e) {
element.appendChild(e.cloneNode(true));
});
}, 300);
#unique_ID {
border: 1px solid blue;
}
<div id="unique_ID"></div>
<div class="a_random_class">a</div>
<div class="a_random_class">b</div>
<div class="a_random_class">c</div>
<div class="a_random_class">d</div>
<div class="a_random_class">e</div>
<div class="a_random_class">f</div>
I've used querySelectorAll
rather than getElementsByClassName
for two reasons:
getElementsByClassName
returns a live list, which makes things awkward when you're copying/moving nodes, because the thing you're looping over keeps changing. We could turn it into an array like this, though:
var arr = Array.prototype.slice.call(document.getElementsByClassName('a_random_name'));
...and then use arr
.
querySelectorAll
is better supported than getElementsByClassName
(IE8, for instance, has querySelectorAll
but not getElementsByClassName
).
Note that that uses the Array#forEach
function even though a NodeList
isn't an array. (More about that here, scroll down to "For Array-Like Objects".) (If you need to support IE8, you'll need to shim/polyfill it or replace it with a plain for
loop.)
Or if you want to move them, just don't use cloneNode
:
setTimeout(function() {
var element = document.getElementById("unique_ID");
element.innerHTML = "";
Array.prototype.forEach.call(document.querySelectorAll(".a_random_class"), function(e) {
element.appendChild(e);
});
}, 300);
#unique_ID {
border: 1px solid blue;
}
<div id="unique_ID"></div>
<div class="a_random_class">a</div>
<div class="a_random_class">b</div>
<div class="a_random_class">c</div>
<div class="a_random_class">d</div>
<div class="a_random_class">e</div>
<div class="a_random_class">f</div>