jQuery JavaScript Code Snippets

This overview is handy towards stepping back and forth between jQuery and JavaScript. First line is jQuery and the following line is the corresponding function in JavaScript.

jQuery

$(document).ready(function() {
  // code…
});

JavaScript

document.addEventListener("DOMContentLoaded", function() {
  // code…
});

jQuery

var divs = $("div");

JavaScript

var divs = document.querySelectorAll("div");

jQuery

var newDiv = $("<div/>");

JavaScript

var newDiv = document.createElement("div");

jQuery

newDiv.addClass("foo");

JavaScript

newDiv.classList.add("foo");

jQuery

newDiv.toggleClass("foo");

JavaScript

newDiv.classList.toggle("foo");

jQuery

$("a").click(function() {
  // code…
})

JavaScript

[].forEach.call(document.querySelectorAll("a"), function(el) {
  el.addEventListener("click", function() {
    // code…
  });
});

jQuery

$("body").append($("<p/>"));

JavaScript

document.body.appendChild(document.createElement("p"));

jQuery

$("img").filter(":first").attr("alt", "My image");

JavaScript

document.querySelector("img").setAttribute("alt", "My image");

jQuery

var parent = $("#about").parent();

JavaScript

var parent = document.getElementById("about").parentNode;

jQuery

var clonedElement = $("#about").clone();

JavaScript

var clonedElement = document.getElementById("about").cloneNode(true);

jQuery

$("#wrap").empty();

JavaScript

var wrap = document.getElementById("wrap");
while(wrap.firstChild) wrap.removeChild(wrap.firstChild);

jQuery

if($("#wrap").is(":empty"))

JavaScript

if(!document.getElementById("wrap").hasChildNodes())

jQuery

var nextElement = $("#wrap").next();

JavaScript

var nextElement = document.getElementById("wrap").nextSibling;
Posted in Tips and Tricks, Windows Tagged with: , ,