Getting an HTML element using a CSS selector with JavaScript
Published on 2024-11-10 • Modified on 2024-11-10
This snippet shows how to get an HTML element using a CSS selector with JavaScript. In the previous snippet, we saw how to select an HTML element by ID or class. This time, we do the same thing with the querySelector()
function which is more flexible than getElementsByClassName
and getElementById()
because we can use a CSS selector. If we want a list instead of an element, we can use the querySelectorAll()
function.
// html => <body lang="en" dir="ltr" id="body-strangebuzz">
const body = document.querySelector('#body-strangebuzz');
console.log('typeof body', typeof body);
console.log('body', body);
if (body !== null) {
console.log('Removing body...')
body.remove();
console.log('Done!')
} else {
console.log('Body not found!')
}
More on Stackoverflow Read the doc More on the web 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! 😉
