Unit 7 ยท JavaScript

7.8.1Accessing elements (by name, ID, class)

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
MethodReturnsUse when
getElementById('x')One elementYou have a unique id
getElementsByClassName('x')CollectionElements share a class
getElementsByName('x')NodeListForm controls by name
getElementsByTagName('x')CollectionAll of a tag type
querySelector('css')First matchAny selector, one element
querySelectorAll('css')NodeListAny selector, many elements