JavaScript
// By ID: returns one element or null
const title = document.getElementById('title');
// By class name: returns a live collection (HTMLCollection)
const notes = document.getElementsByClassName('note');
// By tag name
const items = document.getElementsByTagName('li');
// By name attribute (used for form fields and radio groups): returns a NodeList
const genders = document.getElementsByName('gender');
// Modern and flexible: any CSS selector
const first = document.querySelector('.note'); // first match only
const all = document.querySelectorAll('ul li'); // all matches (NodeList)
notes[0]; // access by index
all.forEach(li => console.log(li.textContent));
Array.from(notes).map(n => n.id); // convert to a real array when needed| Method | Returns | Use when |
|---|---|---|
getElementById('x') | One element | You have a unique id |
getElementsByClassName('x') | Collection | Elements share a class |
getElementsByName('x') | NodeList | Form controls by name |
getElementsByTagName('x') | Collection | All of a tag type |
querySelector('css') | First match | Any selector, one element |
querySelectorAll('css') | NodeList | Any selector, many elements |