Simple Javascript Snippets



A Collection Of Simple Snippets

A small collection of snippets to. Nothing special.. just minimal examples of the bare basics.

Get Element By Id

const thing = document.getElementById('id');

Get Multiple Elements By Class

const things = document.querySelectorAll('.class');

things.forEach(thing => {
  console.log(thing);
});

Get Element By XPATH

function getElementByXpath(path) {
  return document.evaluate(path, document, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue;
}

getElementByXpath('XPATH');

Event Listeners

DOM Loaded

document.addEventListener('DOMContentLoaded', (e)) => {
  // code
});

Click

thing.addEventListener('click', (e) => {
  // code
});

Submit

thing.addEventListener('submit', (e) => {
  e.preventDefault();
  // code
});

Manipulate Class List

Add

thing.classList.add('class');

Remove

thing.classList.remove('class');

Contains

thing.classList.contains('class');

Add Event Listener To Multiple Classes

const things = document.querySelectorAll('.class');

things.forEach(thing => {
  thing.addEventListener('click', (e) => {
    console.log(e.target);
  });
});

Insert CSS Style To Head

const style = document.createElement('style'), styleSheet;
styles = style.sheet;
styles.insertRule("* {color: red;}", 0);
document.head.appendChild(style);

Old Skool Loop

const things = [1,2,3];

for (i = 0; i < things.length; i++) {
  consoe.log(things[i]);
}

Thanks for reading. x

Resources