Getting an HTML element by CSS class with JavaScript

Published on 2024-10-27 • Modified on 2024-10-27

This snippet shows how to get an HTML element by CSS class with JavaScript. The getElementsByClassName function returns an HTMLCollection, so we must test if there is at least one element before trying to remove it.


// html => <body lang="en" dir="ltr" id="body-strangebuzz" class="body-strangebuzz">
function removeBody() {
  const body = document.getElementsByClassName('body-strangebuzz');
  if (body.length > 0) {
    body[0].remove();
  }
}
HTML demo of the snippet
» Click here to delete the body of this page! «

 More on Stackoverflow   Read the doc  Random snippet

  Work with me!