Last active
March 5, 2021 08:00
-
-
Save surjithctly/48d26d4802fa60b2e9d9ed836cc48a70 to your computer and use it in GitHub Desktop.
Vanilla JavaScript Cheat Sheet
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
I always forgot these simple javascript methods. | |
So I can refer this anytime. | |
Surjith S M / @surjithctly | |
**/ | |
//--------------------------------------------------------------------- | |
// Javascript get element by ID | |
const element = document.getElementById("intro"); | |
//--------------------------------------------------------------------- | |
// Javascript get element by Class Name | |
const element = document.getElementsByClassName("menu"); | |
//--------------------------------------------------------------------- | |
// Javascript get element by Tag Name | |
const element = document.getElementsByTagName("p"); | |
//--------------------------------------------------------------------- | |
// Javascript query Selector | |
const element = document.querySelectorAll(".example"); | |
const element = document.querySelectorAll("p.intro"); | |
const matches = document.querySelectorAll("div.note, div.alert"); | |
const container = document.querySelector("#test"); | |
const matches = container.querySelectorAll("div.highlighted > p"); | |
//--------------------------------------------------------------------- | |
// Javascript On Click Toggle Class | |
document.getElementById("menu").onclick = function () { | |
this.classList.toggle("active"); | |
}; | |
//--------------------------------------------------------------------- | |
// Changing Class Names in JavaScript | |
document.getElementById("container").classList.add('block'); | |
document.getElementById("container").classList.remove('hidden'); | |
if ( document.getElementById("container").classList.contains('is-mobile') ) | |
document.getElementById("container").classList.toggle('active'); | |
//--------------------------------------------------------------------- | |
// Javascript Click Event Listener | |
document.addEventListener("click", function(){ | |
document.getElementById("demo").innerHTML = "Hello World"; | |
}); | |
//--------------------------------------------------------------------- | |
// Javascript Click Event Listener as a function | |
document.addEventListener("click", myFunction); | |
function myFunction() { | |
document.getElementById("demo").innerHTML = "Hello World"; | |
} | |
// List of Events | |
// https://developer.mozilla.org/en-US/docs/Web/Events | |
//--------------------------------------------------------------------- | |
// |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment