Get element by ID
Return the element that matches the selector.
let content = document.getElementById( 'some-element' );
Get element by class or ID
Returns the first element that matches the selector.
let element = document.querySelector( '.some-element' );
Toggle class on body element
Adds or removes a class.
const body = document.querySelector( 'body' );
body.classList.toggle( 'some-element' );
Get elements by class or ID
querySelectorAll
returns a static NodeList. Please note that a NodeList is not an array.
var elements = document.querySelectorAll( '.some-element' );
Get elements by class
getElementsByClassName
returns a live HTMLCollection. Please note that a HTMLCollection is not an array.
var elements = document.getElementsByClassName( 'some-element' );
Loop through elements
Most standaard way of doing a loop for an array. This will not work for a HTMLCollection. It will work for a NodeList.
Reference: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach
elements.forEach( function( element ) {
console.log( element );
} )
Loop through elements with for…of loop
The for…of statement executes a loop that operates on a sequence of values. So this will work for a HTMLCollection and a NodeList.
Reference: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for…of
for ( const element of elements ) {
console.log( element );
} )
Add a class
document.classList.add( 'some-element' );
Remove a class
document.classList.remove( 'some-element' );
Onclick event listener
We use the arrow function syntax in the event listener. This is a shorthand way of defining a function expression, introduced in ES6.
element.addEventListener( 'click', () => {
console.log( 'Clicked' );
} );
Hide element
element.style.display = 'none';