Skip to content

Instantly share code, notes, and snippets.

@kkga
Last active March 1, 2022 16:05
Show Gist options
  • Save kkga/8609311 to your computer and use it in GitHub Desktop.
Save kkga/8609311 to your computer and use it in GitHub Desktop.
snippets of plain js
// document.ready
document.addEventListener("DOMContentLoaded", function() {
// your code
}, false);
// select div
var element = document.querySelector("div");
// select all div's inside container
var elements = document.querySelectorAll(".container div");
// select specific element's children
var navigation = document.querySelector("nav");
var links = navigation.querySelector("a");
// reusable dollar function and event binding
var $ = document.querySelectorAll.bind(document);
Element.prototype.on = Element.prototype.addEventListener;
// and how to use it
$(".element")[0].on("touchstart", handleTouch, false);
// select parent node
var parent = document.querySelector("div").parentNode;
// select next node
var next = document.querySelector("div").nextSibling;
// select previous node
var previous = document.querySelector("div").previousSibling;
// select first child
var child = document.querySelector("div").children[0];
// select last child
var last = document.querySelector("div").lastElementChild;
// add class to element and replace all current classes
var element = document.querySelector(".some-class");
element.className = "foo";
// add class to element without replacing current classes
element.className += " foo";
// reusable function to remove certain class
function removeClass(el, cls) {
var reg = new RegExp("(\\s|^)" + cls + "(\\s|$)");
el.className = el.className.replace(reg, " ").replace(/(^\s*)|(\s*$)/g,"");
}
// and how to use it
removeClass(element, "foo");
// reusable function to check if element has class
function hasClass(el, cls) {
return el.className && new RegExp("(\\s|^)" + cls + "(\\s|$)").test(el.className);
}
// and how to use it
if (hasClass(element, "foo")) {
// your code
}
// HTML5 classList API
// add class
element.classList.add("bar");
// remove class
element.classList.remove("foo");
// check if has class
element.classList.contains("foo");
// toggle class
element.classList.toggle("active");
// change HTML content
document.querySelector("h1").textContent = "Hello";
// add/modify HTML attribute
document.querySelector("img").setAttribute("src", "logo.png");
// remove attribute
document.querySelector("#header").removeAttribute("id");
// change style
document.querySelector(".about").style["background"] = "red";
// Manipulating the DOM
// select an element
var element = document.querySelector(".class");
// clone it
var clone = element.cloneNode(true);
// do some manipulation off the DOM
clone.style.background = "#000";
// replace original with the clone
element.parentNode.replaceChild(clone, element);
// add clone to body
document.body.appendChild(clone);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment