Back to Home
DOM

How to Select DOM Elements

Use querySelector() or querySelectorAll()

Quick Answer (2024 ES6+ Way)

javascript
const element = document.querySelector('.my-class');
const allElements = document.querySelectorAll('.my-class');

Live Example

javascript
// Select first paragraph
const firstP = document.querySelector('p');

// Select all buttons
const buttons = document.querySelectorAll('button');

// Work with results
buttons.forEach(btn => {
  btn.style.color = 'blue';
});

Common Variations

Select by ID
javascript
const element = document.querySelector('#myId');
// or
const element2 = document.getElementById('myId');
Select by Data Attribute
javascript
const element = document.querySelector('[data-id="123"]');

❌ Don't Do This (Outdated Way)

Avoid using jQuery or getElementsByClassName

javascript
// DON'T DO THIS
var elements = document.getElementsByClassName('my-class');
// Returns HTMLCollection, not array

Browser Support

Works in all modern browsers (IE8+)

#dom#selector#query