getElementsByClass and appendChild

Snorlax picture Snorlax · Aug 6, 2015 · Viewed 33.5k times · Source

just brushing up on my javascript skills and trying to figure out why getElementsByClass isn't working for my code. The code is pretty simple. Upon clicking a button "clicky", the script will create a child h1 element of div. It works perfectly fine when I use getElementById and changing the div class to Id but doesn't work when I change it to class.

I've tried, getElementsByClassName, getElementsByClass, getElementsByTagName and changing the div to the appropriate attribute but no luck.

<!doctype html>
<html>


<body>
<p>Click on button to see how appendChild works</p>

<button onclick="myFunction()">Clicky </button>

<script>
function myFunction(){
var first = document.createElement("H1");
var text = document.createTextNode("Jason is pretty awesome");
first.appendChild(text);

document.getElementsByName("thistime").appendChild(first);

}
</script>

<div class="thistime">Hi</div>

    </body>






</html>

Answer

Nikhil Aggarwal picture Nikhil Aggarwal · Aug 6, 2015

You need to update your code from

document.getElementsByName("thistime").appendChild(first);

to

document.getElementsByClassName("thistime")[0].appendChild(first);

For reference - https://developer.mozilla.org/en-US/docs/Web/API/Document/getElementsByClassName

Working code - http://plnkr.co/edit/k8ZnPFKYKScn8iYiZQk0?p=preview