getElementsByClassName().classList.remove() returning undefined

I have a Marketo form which I want upon form submission to hide all form elements and show a div (class of “thank-you”), and I keep getting the error Uncaught TypeError: Cannot read property 'remove' of undefined. Any ideas what I may be doing wrong?

Fiddle: https://jsfiddle.net/Ld7fajmy/

HTML

<div class="thank-you hide">
  message
</div>

JS

document.getElementsByClassName("thank-you").classList.remove("hide");

Answer

The getElementsByClassName method returns a collection of all elements in the document with the specified class name, as a NodeList object, so you need access it by passing index

document.getElementsByClassName("thank-you")[0].classList.remove("hide");

Leave a Reply

Your email address will not be published. Required fields are marked *