JavaScript – JS & the DOM

Creating and inserting elements

  • createElement()
  • insertAdjacentHTML()
const newElement = document.createElement('div');
newElement.classList.add('newClass');
message.innerHTML =  'My HTML content';

header.append(message); // or prepend, or before, or after.

message.remove(); // remove element

Other methods etc:

// Styles

message.style.backgroundColor = '#232323'; // use camelCase - sets inline style
getComputedStyle(message).height;

Number.parseFloat(getComputedStyle(message).height, 10) // Gets numeric value of height

document.documentElement.style.setProperty('--color-primary', 'orangered'); // Sets root style variables

// Attributes
myButton.alt; myButton.src; myButton.className;
myButton.getAttribute('customAttribute');
myButton.dataset.versionNumber // gets data-version-number

Smooth Scroll

const btnScrollTo = document.querySelector('.btn-scroll-to');
const section1 = document.querySelector('#section--1');

btnScrollTo.addEventListener('click', function(e) {
  const s1coords = section1.getBoundingClientRect();
}

window.scrollTo({
 left: s1coords.left,
 top: s1coords.top + window.pageYOffset);
 behaviour: 'smooth'
});

// MODERN BROWSERS
section1.scrollIntoView({behaviour: 'smooth'});

// Viewport
document.documentElement.clientHeight document.documentElement.clientWidth

More Events & EventHandlers

const mouseEnterFunction = function(e) {// do something}

message.addEventListener('mouseenter', mouseEnterFunction); // allows you to add multiple event listeners.

// Alternatively - old version
message.onmouseenter = function (e) {};

// Remove
setTimeout(() => message.removeEventListener('mouseenter', mouseEnterFunction), 2000);

Bubbling & Capturing

Event is initially captured at root. Capturing phase goes through all the child elements to the target phase and the passes back (bubbling phase).

Leave a Reply

Your email address will not be published. Required fields are marked *