Skip to main content Accessibility Feedback

Selectors

document.querySelector()

Find the first matching element on a page.

// The first div
var elem = document.querySelector('div');

// The first div with the .bg-red class
var elemRed = document.querySelector('.bg-red');

// The first div with a data attribute of snack equal to carrots
var elemCarrots = document.querySelector('[data-snack="carrots"]');

// An element that doesn't exist
var elemNone = document.querySelector('.bg-orange');

Works in all modern browsers, and IE9+. You can extend support back further with polyfills.