Categories
Javascript Past Tutorials

Quick Tip: Javascript Equivalents to jQuery

If you’re a developer, your initial knee jerk reaction to the “Javascript Equivalents to jQuery” title is, “Hey #$%! it’s the other way around!”

And of course, you are correct. But many of us started with jQuery first. While I’m not one of those, I did find myself relying more and more on jQuery. Now don’t get me wrong, I love jQuery, but I realized as I became more proficient that some of the projects I was working on didn’t include a jQuery library. I could have easily added the library but I began to think about the future. What if this particular client didn’t want a jQuery library included on his site? I wanted to make sure my script would work regardless of the environment, and in order to ensure that, I eventually started writing plain old javascript.

Selectors

My initial attraction to jQuery started with the ease of use of the selectors. I had a hard time memorizing the POJ selectors, and memorizing $(“element”) is easier that remembering camel humped run-on sentences. BUT I paid for it in the long run. Don’t repeat my mistakes, learn your selectors:

Select by id

$("#id")
document.getElementById("id")

Select by class

$(".class")
document.getElementsByClassName("class")

Select by query

$("#id .class")
document.querySelectorAll("#id .class")

Setting Styles

Setting styles is very convenient in jQuery, I’m pretty sure you are familiar with the following:

$("element").css("background", "red")

It’s also pretty simple in Plain Old Javascript

el.style.background = "red"

HTML

Get HTML

$("element").html()
element.innerHTML

Set HTML

$("element").html("<h3>Set HTML</h3>")
element.html = "<h3>Set HTML</h3>"

Loop (Each)

$("selector").each(function(i, el){
   console.log("key:" + i + " => " + "value:" + el)
});
var elements = document.querySelectorAll(selector);

Array.prototype.forEach.call(elements, function(el, i){
   console.log("key:" + i + " => " + "value:" + el)
});