Web Platform Javascript

DOM Manipulation

Read more about the Element class where most of these functions reside.

In most of the examples here, el represents a variable containing an element. See Getting a reference to an element for how to do this.

See also: DOM visuals manipulation - getting the size of things, changing scrolling, moving things around

Getting a reference to an element

If your element has a unique id, eg <div id="startBtn">Start</div>, you can usedocument.getElementById` to get a reference to it in Javascript.

document.getElementById('startBtn').addEventListener('click', () => {
    // Handle click...
});

Note that in CSS, ids are prefixed with a '#' symbol. This is not used with getElementById.

Use getElementsByClassName to get items that have a class.

document.getElementsByClass('someClass');

Use querySelectorAll to find an item based on a selector. It returns a list of all matching elements. The syntax used here matches that used in CSS.

const matches = document.querySelectorAll('nav #bar.someClass'); // returns a NodeList of matches

// If you want, you can convert the NodeList to a normal array
const matchesAsArray = Array.from(matches);

Example, toggling the class of every element with the 'details' class.

const details = document.getElementsByClassName('detail');
for (let el of details) {
  el.classList.toggle('hidden');
}

To check whether an element contains a matching child, call querySelector on an element rather than the root document.

if (parentEl.querySelector('.blah') !== null) {
    // Yes, parentEl contains something with class 'blah'
}

To check whether an element matches a given selector:

if (el.matches('.blah')) {
    // Yes, el has the class 'blah'!
}

Read more

Classes

Use add, remove and toggle on an element's classList property.

el.classList.add('expanded');
el.classList.remove('expanded');
el.classList.toggle('expanded');

contains returns true if the element contains the class:

if (el.classList.contains('expanded')) {
    // Yes, it does!
}

Inserting

Insert raw HTML next to an element with insertAdjacentHTML.

el.insertAdjacentHTML(position, html);

You can use the following values for position: beforeBegin, afterBegin, beforeEnd, afterEnd.

Example:

el.insertAdjacentHTML('afterEnd', '<em>Extra</em>');

Read more

Rather than adding elements as strings you can also create them and add them in a more manual way. This can be preferred if you want to attach event handlers at the same time

// Create an element based on tag
const newEl = document.createElement("span");
newEl.innerText = 'Hello';
newEl.addEventListener('click', () => console.log('Clicked!'));
el.appendChild(newEl); // Add newly-made SPAN to el

Moving

Once you have an element reference (by creating it using creatingElement or using a selector query), you can move it to a new parent:

// Add thingToMove to parentElement
parentElement.appendChild(thingToMove);
// Insert thingToMove before referenceNode in parentElement
parentElement.insertBefore(thingToMove, referenceNode)

Read more

Removing

el.remove();

Attributes

Does an element have an attribute?

if (el.hasAttribute('my-data')) {
    // yes!
}

Get the value of an attribute

const r val = el.getAttribute('my-data');

Set the value of an attribute

el.setAttribute('my-data', 'blue');

Remove an attribute

el.removeAttribute('my-data');

Read more:

HTML/Text content

Getting:

const outerHtml = el.outerHTML;
const innerHtml = el.innerHTML;
const text = el.textContent;

Setting:

el.outerHTML = '<em>New</em>';
el.innerHTML = '<em>New</em>';
el.textContent = 'New';

Read more

Traversing the DOM tree

Try the following properties available on elements: previousElementSibling, nextElementSibling, parentNode, firstElementChild, lastElementChild.

Example:

// Remove the element after el
const siblingEl = el.nextElementSibling;
siblingEl.remove();

The 'offset parent' refers to parent element which has a set position. This can be useful for relatively located elements to find their absolute position.

const offsetParent = el.offsetParent;

Count child elements:

const contains = el.childElementCount;

Do something with child elements with the children collection.

const children = el.children;
for (let childEl of children) {
    // do something with every element inside of el...
}

It could also be traversed as an array if counting through them is needed:

const children = el.children;
for (let i; i<children.length; i++) {
    // do something with children[i]
}

Read more