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
Call to action
Did you like this post? You can help me back in several ways: (use the "reply" link on the right to comment or to contact me )
- Report any error/typo.
- Report something that could be improved.
- Like and repost!
- Follow me on Bluesky 🦋
- Subscribe to the RSS feed.
- Click on the More on Stackoverflow buttons to make me win "Announcer" badges 🏅.
Thank you for reading! And see you soon on Strangebuzz! 😉