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!')
}
HTML demo of the snippet
» Click here to delete the body of this page! «
More on Stackoverflow Read the doc More on the web Random snippet