Skip to content

Instantly share code, notes, and snippets.

@joyrexus
Last active January 22, 2024 21:15
Show Gist options
  • Star 36 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save joyrexus/5322252 to your computer and use it in GitHub Desktop.
Save joyrexus/5322252 to your computer and use it in GitHub Desktop.
Comparison of jQuery and vanilla JS for basic DOM manipulation.

jQuery vs native JS

Selecting Elements

var divs = $("div");

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


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

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


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

var nextElement = document.getElementById("wrap").nextSibling;

Setting Attributes

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

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

Creating Elements

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

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

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

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

Cloning Elements

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

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

Removing Elements

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

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

Testing for child nodes

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

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

Adding Classes

newDiv.addClass("foo");

newDiv.classList.add("foo");

Toggling Classes

newDiv.toggleClass("foo");

newDiv.classList.toggle("foo");

Adding Events

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

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

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

document.addEventListener("DOMContentLoaded", function() {
  // code
});
@PleachiM
Copy link

I was searching for exactly such an example :) Thank you

@AYZBTR
Copy link

AYZBTR commented Jan 22, 2024

I'm grateful to have discovered the exact example I was seeking!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment