Skip to content

Instantly share code, notes, and snippets.

@shyamvkansagra
Last active October 18, 2021 20:43
Show Gist options
  • Save shyamvkansagra/6cd901bf0bc2345b8d28ee421acfc922 to your computer and use it in GitHub Desktop.
Save shyamvkansagra/6cd901bf0bc2345b8d28ee421acfc922 to your computer and use it in GitHub Desktop.
This document lists some easy to use utility type functions when you want to replace jQuery with javascript. Also it describes few commonly used selectors and their equivalent javascript code.

Here I have listed jQuery selectors, their meanings and their equivalent javascript code to replace. Also, when code gets repetitive, I had created some util functions too which we can simply call and use.

Check out util functions: To create some for your code, you can create a global variable (if needed) and add our custom methods in it. This saves repetition of the code and feels like you are writing a library functions which can be used from anywhere.

window.Utils = {}

Utils.insertBefore = function(elemStrToAttach, insertPlaceElem) {
  var elemToInsert = SwymUtils.createElement(elemStrToAttach);
  insertPlaceElem.insertAdjacentElement('beforebegin', elemToInsert);
};

Utils.forEachNodeElem = function(elems, callback) {
    for (var i = 0, len = elems.length; i < len; i++) {
      callback(elems[i]);
    }
};

Utils.createElement = function(nodeContent) {
    var dFrag = document.createDocumentFragment();
    var tempNode = document.createElement('div');
    tempNode.innerHTML = nodeContent;
    node = tempNode.children[0];
    dFrag.appendChild(node);
    return node;
};

Utils.forEachElement = function(selector, fn, elem) {
    var elements = (elem || document).querySelectorAll(selector);
    for (var i = 0; i < elements.length; i++)
      fn(elements[i], i);
};

Utils.showElem = function(el, displayVal) {
    if (el) {
      el.style.display = displayVal || '';
    }
};

Utils.hideElem = function(el, displayVal) {
    if (el) {
      el.style.display = displayVal || 'none';
    }
};

Utils.removeClass = function(el, className) {
    if (el.classList) {
      className.split(" ").forEach(function(c) {
        el.classList.remove(c);
      });
    } else {
      el.className = el.className.replace(new RegExp('(^|\\b)' + className.split(' ').join('|') + '(\\b|$)', 'gi'), ' ');
    }
};

Utils.addClass = function(el, className) {
    if (el.classList) {
      className.split(" ").forEach(function(c) {
        el.classList.add(c);
      });
    } else {
      el.className += ' ' + className;
    }
};

Find the list of commonly used jQuery selectors, their meaning and js equivalent below:

Notes:

  • Wherever "element" is written, it specifies a DOM element

  • If Utils is used, refer the code from above

  • To work on single element, use document.querySelector and to traverse all elements, use Utils.forEachElement or use Utils.forEachNodeElem.



  • attr

Example: $(".className").attr("data-abc");

Meaning: Can get or set attribute of DOM element

javascript: element.setAttribute("data-abc", "xyz"); or element.getAttribute("data-abc")



  • each

Example: $.each(".className", function(val) {})

Meaning: Traverse all the elements(array, can be used for objects too, but lets keep this specific to DOM) returned by selectors and do some action

javascript: Utils.forEachElement(".className", function(elem) {})



  • on

Example: $(".className").on("click", function() {})

Meaning: Get element/s and add some event based function

javascript: Utils.forEachElement()



  • parent

Example: $(".className").parent()

Meaning: Get parent element of a desired element

javascript: element.parentNode()



  • Regular selector

Example: $(".className")

Meaning: Select all elements specified by given selector

javascript: document.querySelectorAll(".className")



  • insertBefore

Example: $("<p>Test</p>").insertBefore(".inner")

Meaning: Insert an element at desired location

javascript: Utils.insertBefore("<p>Test</p>", ".inner")



  • change

Example: $(".target").change(function() {})

Meaning: For specified elements, add "change" event listener function

javascript: Utils.forEachElement(".target", function(elem) { elem.addEventListener("change", function() {}) })



  • append

Example: $(".inner").append("<p>Test</p>")

Meaning: Append an element to specified elements

javascript: Utils.forEachElement(".inner", function(elem) { elem.appendChild(Utils.createElement("<p>Test</p>")) })



  • show

Example: $(".target").show()

Meaning: Display a certain hidden element/s

javascript: Utils.showElem(document.querySelector(".target")) // assuming only one elem is present, use Util to select all



  • clone

Example: $(".hello").clone()

Meaning: Create a copy of a DOM element, returns new element

javascript: document.querySelector(".hello").cloneNode(true)



  • addClass

Example: $("p").addClass("myClass yourClass")

Meaning: Add a desired class names to an element/s

javascript: Utils.addClass(document.querySelector("p"), "myClass yourClass")



  • hide

Example: $(".target").hide()

Meaning: Hide desired element/s from display on screen

javascript: Utils.hideElem(document.querySelector(".xyz"))



  • find

Example: element.find("a")

Meaning: Find element/s inside a desired DOM element

javascript: element.querySelectorAll("a")



  • remove

Example: elem.remove()

Meaning: Remove an element from the DOM

javascript: element.parentNode.removeChild(element)



  • removeClass

Example: element.removeClass("myClass")

Meaning: Remove a class name from desired DOM element

javascript: Utils.removeClass(element, "myClass")



  • toggleClass

Example: element.toggleClass("myClass")

Meaning: Toggle a class based on some event, event can be any event

javascript: Utils.toggleClass(element, "myClass")



  • html

Example: element.html("<p>Text</p>")

Meaning: Add or change html of desired element

javascript: element.innerHTML = "<p>Test</p>"

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