Returns a live HTMLCollection of elements with the specified class:
const items = document.getElementsByClassName('item');// Returns a live collection that updates automatically// Convert to array to use array methodsconst itemsArray = Array.from(items);
getElementsByClassName returns a live HTMLCollection, meaning it automatically updates when elements are added or removed from the DOM.
const form = document.getElementById('my-form');const inputs = form.querySelectorAll('input, textarea, select');// Or get form elements directlyconst formElements = form.elements;const emailInput = form.elements['email']; // by name attributeconst emailByIndex = form.elements[0]; // by index
// Elements with specific attributeconst withDataId = document.querySelectorAll('[data-id]');// Elements with specific attribute valueconst active = document.querySelectorAll('[data-status="active"]');// Elements with attribute starting with valueconst external = document.querySelectorAll('[href^="http"]');// Elements with attribute ending with valueconst pdfLinks = document.querySelectorAll('[href$=".pdf"]');// Elements with attribute containing valueconst emailLinks = document.querySelectorAll('[href*="mailto"]');
const element = document.getElementById('my-element');if (element.matches('.active')) { console.log('Element is active');}if (element.matches('button.primary, a.primary')) { console.log('Element is a primary button or link');}
Don’t query the DOM repeatedly for the same element:
// Bad - queries DOM 3 timesfor (let i = 0; i < 100; i++) { document.getElementById('counter').textContent = i;}// Good - queries DOM onceconst counter = document.getElementById('counter');for (let i = 0; i < 100; i++) { counter.textContent = i;}
// Slower - searches all elementsconst element = document.querySelectorAll('*').filter(el => el.id === 'target');// Faster - direct selectionconst element = document.getElementById('target');// Medium - CSS selectorconst element = document.querySelector('#target');
getElementById is generally faster than querySelector('#id') because it’s optimized for ID lookups. However, the difference is usually negligible.
Flexibility
querySelector is more flexible as it accepts any CSS selector, while getElementById only works with IDs.
Return type
Both return a single element or null. getElementById is more specific and only works with IDs.
When to use which
Use getElementById when you specifically need to find an element by ID. Use querySelector for more complex selections or when you need CSS selector flexibility.