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++) {
console.log(things[i]);
}
Check If IE (Internet Exporer) OR Edge
if ((navigator.userAgent.indexOf('MSIE') && !!navigator.userAgent.match(/Trident.*rv\:11\./)) || navigator.userAgent.indexOf('Edge') != -1) {
console.log('Loser');
}
Use Python Print Function As Console Log (just for fun)
const print = (s) => {
console.log(s)
}
print('hello world')
Thanks for reading. x
Resources
- Javascript: https://javascript.com