Finding HTML Elements

This YouTube video was created by Steve Griffith.

getElementById()

The getElementById()open in new window function returns a single element whose id matches the string provided. If no element is found with the matching id, null will be returned.

const box = document.getElementById('box')

NOTE

Since element IDs are required to be unique if specified, getElementById() is considered the best way to find a specific element.

textContent

The textContentopen in new window property provides access to an HTML element's text content. This property can be used to access and update an element's text content.

const $box = document.getElementById('box')
$box.textContent = 'I am a box.'

querySelector()

The querySelector()open in new window function returns a single element through the use of a CSS Selector. In the case that a CSS Selector matches more than one element, the first element matched will be retrieved.

const $box1 = document.querySelector('.box')

Any valid CSS Selector will work with querySelector().

// using tags and pseudo-classes
const $box2 = document.querySelector('div:nth-child(2)')
// using attributes
const $box3 = document.querySelector('[data-color]')

In the example below, three different CSS selectors are used to retrieve each of the three boxes and set the background color and text.

querySelectorAll()

The querySelectorAll()open in new window function returns all the elements as a list that match the provided CSS Selector. Using the Array returned, it is possible to manipulate all of the matched elements.

const $boxes = document.querySelectorAll('.box')

In the example below, all the boxes except the second one are retrieve using the querySelectorAll() function and the :notopen in new window selector.