Getting elements using a CSS selector (not jQuery)

Learn how to get a DOM element via a CSS selector without using jQuery.
Tutorials JavaScript

Until recently, I discovered that you can retrieve HTML DOM elements using CSS selectors. This can be done by calling document.querySelector('.your-class') in your JS code. Previously, I was using jQuery to do this.

Here is an example:

// Instantiate the existing button DOM element.
const buttonElement = document.querySelector('.my-button');

// Click the button.
buttonElement.click();

Here’s what the HTML would look like, keeping it Vanilla JS:

<!-- The button that will be clicked by JS, and maybe by you too. :-) -->
<button class="my-button" onclick="alert('Hello, world!');">My very special button</button>

You can see an example of this in CodePen here. Notice how when you load the page, you get the alert pop-up displaying “Hello, world!” This means the JavaScript is clicking the button.

© 2019 - 2021 Brian McVeigh