.Maui Blog

jQuery to pure Javascript examples – 1

With this post, we want to inaugurate a post series of examples to see how nowadays it is easy to replace jQuery with pure javascript.
This is because with the new javaScript standards major web browsers already supporting most of the features in jQuery, we can thus avoid loading extra javascript on our website.
In this post, we’ll start with the most common functions.

Get Element by Id

// jQuery.
let my_elm = $("#myElm");

// Pure Javascript
let my_elm = document.getElementById("myElm");

Get Value

// jQuery.
let my_value = $("#myElm").val();

// Pure Javascript
let my_value = document.getElementById("myElm").value;
// or more simply
let my_value = myElm.value;

Get Element by Class

// jQuery.
let my_elm = $(".my-class");

// Pure Javascript
let my_elm = document.querySelector(".my-class");

Get Elements by Attribute

// jQuery.
let my_elms = $("[type=radio]");

// Pure Javascript
let my_elms = document.querySelectorAll("[type=radio]");

For each

// jQuery.
$("[type=radio]").each(function(){
    console.log($(this).val());
});

// Pure Javascript
document.querySelectorAll("[type=radio]").forEach(function(item) {
    console.log(item.value);
});
Exit mobile version