DEV Community

Munieru
Munieru

Posted on

I Need jQuery

It has been a long time since you said "You Don't Need jQuery", but it's still useful for doing DOM operation in user script etc.1

Get elements

In native, element getter methods has too many kinds and has too long name.
In jQuery, $() is all.

Get element by selector

Native

const viewport = document.querySelector('meta[name=viewport]');
Enter fullscreen mode Exit fullscreen mode

jQuery

const $viewport = $('meta[name=viewport]');
Enter fullscreen mode Exit fullscreen mode

Get elements by selector

Native

const externalLinks = document.querySelectorAll('a[target=_blank]');
Enter fullscreen mode Exit fullscreen mode

jQuery

const $externalLinks = $('a[target=_blank]');
Enter fullscreen mode Exit fullscreen mode

Get elements by class

Native

const articles = document.getElementsByClassName('article');
Enter fullscreen mode Exit fullscreen mode

jQuery

const $articles = $('.article');
Enter fullscreen mode Exit fullscreen mode

Get element by id

Native

const main = document.getElementById('main');
Enter fullscreen mode Exit fullscreen mode

jQuery

const $main = $('#main');
Enter fullscreen mode Exit fullscreen mode

Get elements by name

Native

const buttons = document.getElementsByName('button');
Enter fullscreen mode Exit fullscreen mode

jQuery

const $buttons = $('[name=button]');
Enter fullscreen mode Exit fullscreen mode

Get elements by tag name

Native

const links = document.getElementsByTagName('a');
Enter fullscreen mode Exit fullscreen mode

jQuery

const $links = $('a');
Enter fullscreen mode Exit fullscreen mode

Set styles

In native, You can't set multiple styles to element at once.
In jQuery, jQuery.css() can that.

Native

element.style['background-color'] = '#000000';
element.style['color'] = '#ffffff';
Enter fullscreen mode Exit fullscreen mode

jQuery

$element.css({
  'background-color': '#000000',
  'color': '#ffffff'
});
Enter fullscreen mode Exit fullscreen mode

Create element from HTML string

In native, You need to cast long spell to create element from HTML string.
In jQuery, $() can that.

Native

const foo = document.createRange().createContextualFragment(`<div id="foo">Foo</div>`);
Enter fullscreen mode Exit fullscreen mode

jQuery

const $foo = $(`<div id="foo">Foo</div>`);
Enter fullscreen mode Exit fullscreen mode

Set display state

In native, You need to rewrite value of display property to change display state of element.
In jQuery, there are several intuitive methods.

Show element

Native

element.style.display = 'block';  //or 'inline', 'inline-block', 'inline-table'...
Enter fullscreen mode Exit fullscreen mode

jQuery

$element.show();
Enter fullscreen mode Exit fullscreen mode

Hide element

Native

element.style.display = 'none';
Enter fullscreen mode Exit fullscreen mode

jQuery

$element.hide();
Enter fullscreen mode Exit fullscreen mode

Toggle display

Native

const elementIsShowing = element.ownerDocument.defaultView.getComputedStyle(element, null).display !== 'none';
element.style.display = elementIsShowing ? 'none' : 'block';  //or 'inline', 'inline-block', 'inline-table'...
Enter fullscreen mode Exit fullscreen mode

jQuery

$element.toggle();
Enter fullscreen mode Exit fullscreen mode

Other Language


  1. In my own application, I will use Vue.js etc. ↩

Top comments (36)

Collapse
 
maxart2501 profile image
Massimo Artizzu • Edited

I Need jQuery

No, you don't. You can find it useful, and that's fine. It makes you feel more comfortable with front-end coding. Another perfectly valid reason.

But you don't need jQuery.

Also, looking at your examples, I find that maybe jQuery has prevented you to consider some recent but common new features in browsers. For example:

In native, You can't set multiple styles to element at once.

Sure you can. Consider this:

Object.assign(element.style, {
  'background-color': '#000000',
  'color': '#ffffff'
});
Enter fullscreen mode Exit fullscreen mode

More than that, you must be aware of what jQuery does for every operation. It creates a collection, attaches its methods, bindings and callbacks. It performs its checks. It has a cost. And everyone should be aware of that.

That's why it's wrong to compare .hide() to simply setting .style.display = 'none': in fact, the former does much more than the latter, and should generally be avoided.

In native, element getter methods has too many kinds and has too long name.

This is a non-issue, as you can use a plethora of tools that help you writing your code with intellisense and the like.

Anyway, performing DOM operations should be hardly be an issue nowadays. You should concentrate on the structure of your application, and jQuery doesn't help in that sense.

All in all, we still have to deal with legacy code that has to maintained, and jQuery is ubiquitous there. So, should I know jQuery? Absolutely. Should I start a project using jQuery? If it's not just a simple landing page, no.

Collapse
 
satya164 profile image
Satyajit Sahoo

Come on, it's not realistic to load a big library just because DOM API is "too long". Create some helpers if you care about the character counts.

Regarding, querying API has "too many kinds", all other queries are possible by just using querySelectorAll.

Collapse
 
sunnysingh profile image
Sunny Singh

I think this article was meant as a joke, but I do agree that creating some helpers is better than loading in a library that also handles many other things.

Collapse
 
bigbott profile image
bigbott

27 kb gzipped is a big library? Nonsense.

Collapse
 
satya164 profile image
Satyajit Sahoo

Yes it is

Collapse
 
ericschillerdev profile image
Unfrozen Caveman Dev

The controversy in the comments makes me laugh anytime someone thinks jQuery is dead. Of course there's specialized stuff that makes some of these things easier in some instances, and as JS evolves, it adds some of this, but it's not dead, and doesn't need to be.

Thanks for keeping this alive, because sometimes you don't need a whole framework to to the little things, and sometimes there's so much specialization that no one framework will cover it well.

Anyone who gets cranky about a tech. that other people are using is either posturing or doesn't know the whole story about an individual project. There's a lot of legacy stuff out there, including browsers that sometimes have to be targeted -- better than it used to be, but still an issue.

Yes, jQuery is getting slowly replaced, but there's no reason to stop showing people how to do the basics until they can pop a framework (sometimes you don't know the best one to use in a given instance) in or upgrade their legacy stuff. Sometimes you just need to know what the previous people did so you CAN replace it with newer ES versions or framework code. Sometimes you need to get it past an entrenched IT team that has whitelisted jQuery libs but not necessarily approve of the latest and greatest yet.

For those laughing at the last bit, or refusing that kind of work, I'm happy to collect your paycheck once I'm done with my stints doing data integration work that you're also refusing.

Collapse
 
aurelkurtula profile image
aurel kurtula

I still think it would be better to use JS. You are not taking in consideration the code behind $.

Also you can use querySelector or querySelectorAll to select you tags, ids and classes, hence you don't need document. getElement...

For styles

// Set multiple styles in a single statement
elt.style.cssText = "color: blue; border: 1px solid black"; 
// Or
elt.setAttribute("style", "color:red; border: 1px solid blue;");

No need to set one style at a time.

Adding html strings, I like this way:

var div = document.createElement('div');
div.innerHTML = '<p>blah</p>';

Toggle

.classList.toggle('className');

Most importantly, you learn js and don't load more code then you need

Collapse
 
facundocorradini profile image
Facundo Corradini • Edited

querySelector and getElement are completely different beasts.

querySelectorAll will return a static collection, while getElementsByClassName returns a live collection. This could lead to confusion if you store the results in a variable for later use:

A variable generated with querySelectorAll will contain the elements that fulfilled the selector at the moment the method was called.
A variable generated with getElementsByClassName will contain the elements that fulfilled the selector when it is used (that may be different from the moment the method was called).

Also getElements allow for a single Id or a single class, while query selector can use complex CSS 3 selectors.

And getEllements is a better performer by orders of magnitude

So both tools have their uses

Collapse
 
aurelkurtula profile image
aurel kurtula

Nice!

Collapse
 
bgadrian profile image
Adrian B.G.

There are other advantages like jQuery caches the selectors.

You can also import only jQuery small functions and use those.

Ppl say we don't need jQuery anymore because we moved to webComponents, to use jQuery there is like playing God and is not good to overwrite the internal state of a comp from outside, aka react, vuejs.

I would still use jQuery for small static websites like landing pages or if I want to make a quick solution.

Collapse
 
remejuan profile image
Reme Le Hane

So you would rather load in 100kb of vanilla js, so that you can use $ instead of just using vanilla js... So glad I don't work with you...

Collapse
 
bgadrian profile image
Adrian B.G.

You are clearly too narrow minded to have a conversation, so no use to reply, and you didn't even read my message.
I think the author didn't presented the advantages of jQuery (poor selection of examples), and by your example clearly you don't know what jQuery is composed of (the sizzle, selector is only a small part of it).

Thread Thread
 
remejuan profile image
Reme Le Hane

As a developer of almost 15 years, it's been at least 8 since I used jQuery, while it can potentially add value, that is far offset by the cost of its inclusion, 100% of which can very easily be done without it, if you are a competent developer.

Thread Thread
 
chocolim profile image
Choco Lim

If you start to do your own js, it will work in a very competent way, until a browser update with a new standard. If you use jQuery or other maybe you have only to update the library and not rework it for all diferent browsers. (sorry for my bad english)

Thread Thread
 
remejuan profile image
Reme Le Hane

Or more likely because you now have a hard dependacy on a boat load of code you never needed, that upgrade comes with breaking changes doing more harm and wasting more time than if you had just done it properly from the start.

Its your slow underperforming website, not mine.

Thread Thread
 
chocolim profile image
Choco Lim

Why use a sdk if you can write assembler code rigth?

Thread Thread
 
remejuan profile image
Reme Le Hane

Ya, you clearly do not understand cost value analysis, while I at no point said jQuery does not add value, in the vast majority of implications the cost far exceeds the value.

I write high performance we applications, up until the day I come across an application that will make 100% utilisation of every feature jQuery has, then all its doing is slowing down my application with code I DO NOT NEED AND CANNOT EXCLUDE.

Every application I wrote only ever has the code it needs, nothing more. Performance is king, no wasted wasted space, no unnecessary bloat.

Thread Thread
 
chocolim profile image
Choco Lim

I do understand actually, but since I am not programing a kernel module using jquery, I am ok with it.

Thread Thread
 
bgadrian profile image
Adrian B.G.

You clearly haven't used a profiler to compare how a 40kb code that is not executed improves your performance. You just throwing big words or your websites has to run on fridges and TVs.

Collapse
 
loilo profile image
Florian Reuschel

Btw some native styling hint if you have modern browsers at hand - the following is possible:

Object.assign(element.style, {
  color: 'red',
  fontSize: '24px',
  // and so on
})
Collapse
 
lexlohr profile image
Alex Lohr

If you really do such low-end stuff exclusively, you should really be able to do it without the whole of jQuery. On the other hand, if you want to do more advanced front-ends, you should definitely go without jQuery and let a framework like preact or Vue manage the DOM for you.

Also, you should not use style or shorthands like .hide() unless there's no other option. Better set class names (like .hidden, [hidden]) and handle them in CSS.

Collapse
 
4rontender profile image
Rinat Valiullov • Edited

Some notes:

In native JS you can add several css styles to element:

div.style.cssText="color: red !important; \
    background-color: yellow; \
    width: 100px; \
    text-align: center; \
    blabla: 5; \
  ";

But you have some restriction: style.cssText overrides previous properties style

Collapse
 
facundocorradini profile image
Facundo Corradini

Well, I think jquery Is still a valid option when you just want to make a simple website, which makes for 99% of the websites out there. There's no need to go react or vue if you're not really gonna be building an app-like kind of thing.

JQuery gets too much undeserved hate lately, because some people that got a sort of addiction to it and can't code 3 lines of JavaScript without it.

Sure, it was much more relevant in the dark ages of CSS 2 and crappy js, but even today, it's a valid tool for some works.

The key is to know when and why use each tool. (Which btw, the post makes an awful job at)
If all you got is a hammer, all tasks will look like nails.
Sometimes vanilla js will do, sometimes you need to go with a modern framework like vue or react, and sometimes the good ol' jquery will work just fine. Heck, nowadays most of what we used jquery for back in the day can now be achieved with CSS 3 and the simplest event listeners

I might not use it anymore , but I refuse to speak badly of a tool that provided us with such a great experience in the past. Which also means we might have to maintain legacy jquery code for a long, long time.

Collapse
 
sournyb profile image
Brahim Sourny

Hi, in case. Here is some helpers functions:

// Select Element by ID
const selectIdElement = (element) => {
return document.querySelector(element);
};

// Select Element by class, id or tag name
const selectXElement = (element) => {
return document.querySelector(element);
};

// Select All Element That have the same attribute
const selectAll = (element) => {
return document.querySelectorAll(element);
}

// Select the parentNode
const selectParent = (element) => {
return document.querySelector(element).parentNode;
}

// Select the ChildNode
const selectChild = (element) => {
return document.querySelector(element).children;
}

// Create HTML element
const createElement = (element) => {
return document.createElement(element);
}

// Create text node
const createTxtNode = (element) => {
return document.createTextNode(element);
}

// Append Element to the DOM
const appendElement = (parentElement, childElement) => {
return parentElement.appendChild(childElement);
}