DEV Community

loading...

Discussion on: JQuery Footguns?

Collapse
jorgecc profile image
Jorge Castro • Edited

Some people preach against jquery but jquery is still a big handy.

  • It doesn't need a polyfill, so it is one problem less. Unless you are using a modern version of jquery. Personally, I don't see the reason to jump over Jquery 3.x

  • Missing object

$("#textbox").html("hi"); // will not crash if textbox doesn't exist
document.getElementById("textbox").innerhtml="hi"; // will crash if textbox exist.

It is because $() always returns a jquery object, not a DOM object.

  • cache
$("#textbox").html("hi")
$("#textbox").html("hi again")

This code is calling to the DOM twice and it's searching for the object textbox. In this case, the object must be cached as follow

let obj=$("#textbox");
obj.html("hi");
obj.html("hi again");
Collapse
deciduously profile image
Ben Lovy Author

Thanks for this! Great point that you always get back a JQuery object - those extra null checks are clunky otherwise.

Collapse
rhymes profile image
rhymes

One thing I just remembered:

I used to use a convention to distinguish jQuery objects from regular variables, stuff like var $textBox = $("#textBox"). Don't know if it still makese sense but it did at the time :D

Collapse
peiche profile image
Paul

I've also been doing this for a long time. It's very handy.

Collapse
deciduously profile image
Ben Lovy Author

Oh, I like that a lot. Most likely stealing this.