Javascript functions and methods

Get element by ID

Return the element that matches the selector. This will return an object.

const content = document.getElementById( 'some-element' );

Get element by class or ID

Returns the first element that matches the selector. This will return an object.

const element = document.querySelector( '.some-element' );

Get elements by class, ID or data attribute

querySelectorAll returns a static NodeList. Please note that a NodeList is not an array. But you can use methods like forEach.

const elements = document.querySelectorAll( '.some-element' );

Get elements by class

getElementsByClassName returns a live HTMLCollection. Please note that a HTMLCollection is not an array. You can easily transform this to an array with Array.from( elements ).

const elements = document.getElementsByClassName( 'some-element' );

Toggle class on body element

Adds or removes a class.

const body = document.querySelector( 'body' );

body.classList.toggle( '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. Transform a HTMLCollection to an array with Array.from( elements ).

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';

Get attribute

element.getAttribute( 'data-some-attribute' )