7 ms·
A summary of jQuery method alternatives in native browser implementation
- grabcocque 10y agoWhy use JQuery when you can do it in a way that's more ugly, more verbose, less portable, more likely to break?
- zepolen 10y agoMostly agree, but there are use cases like performance where it's best to go as low level as possible.
- metalelf0 10y agoThis is exactly what I came here to type. Or, you can take all the vanilla js snippets, wrap them into a shorter notation... and build your own jQuery, just with less portability. I don't get the point of this.
- fiiv 10y agoJQuery is massive and has a lot of functionality. Sometimes this is nice, but sometimes all you need from it is a small part of that whole. I think the point of that link is that if you are looking to build in some simple functionality like hide and show an element when someone clicks a button, then you do not really need to include the whole JQuery library just to do that because then the massive library is not being used and you would be better served to write your own vanilla function. I don't see anything wrong with that. No one is saying that JQuery sucks or that it should die, I think the point is more "use the best tool for the job". You can buy a massive wrench with all kinds of adjustable settings and addons and stuff but if all you ever need is an Alan key, then maybe the little one that comes with your IKEA furniture is actually better and easier to use than that massive wrench.
- drinchev 10y agoNo jQuery actually means: 1. Less dependencies for your JavaScripts 2. Less "magic" behind the scenes 3. Native JS-engine optimisation 4. Switch of though-process ( jQuery, although quite flexible ), makes you think that everything is "string", "array", "object" and sometimes you need the bare Node-element e.g. https://developer.mozilla.org/en-US/docs/Web/API/Element https://developer.mozilla.org/en-US/docs/Web/API/Element
- squeral 10y agoYou can always use TypeScript if you want your code to look prettier and more verbose.
- izolate 10y agoNext phase: You Don't Need Native APIs, use React. Source: lamenting the fact that I haven't used querySelector in almost a year.
- pluma 10y agoNote: you can use `querySelector` on elements other than the root element. This can be helpful if you need to use React's `ref` escape hatch to do something "low-level".
- nautical 10y agoI actually tried using plain JS in recent projects of mine , here`s my take . If it is a simple 3-4 page website I write it in plain JS , if it is a complex website with lots of views and components I write in Vue + plain JS (if req).
- kibibu 10y ago// jQuery $el.siblings(); // Native Array.prototype.filter.call(el.parentNode.children, (child) => child !== el ); Yes, much clearer
- petepete 10y agoWhile I'm firmly of the opinion that full jQuery is a fine choice for most projects, if you don't need `$.animate` or favour fetch over `$.ajax` you might be better-served choosing the slim build or smaller libraries that provide only a subset of jQuery's functionality (Domtastic, Zepto, etc)
- pluma 10y agoAlternatively: Array.from(el.parentNode.children).filter( (child) => child != el ) But yes, it's not quite as sexy as siblings().
- dageshi 10y agoI really don't get this vendetta some small number of people seem to have against jQuery. It seems like it gets looked down upon in the same way that PHP gets looked down upon. But while PHP has legitimate problems most arguments against jQuery seem to boil down to "You can save a 100k download!". Big deal.
- forestjc 10y agowhat kind of problems has PHP?
- tudorw 10y agotoo old, like me :) Seriously, https://symfony.com/ https://symfony.com/ is awesome.
- amiga-workbench 10y agoNot hip or edgy enough.
- mkawia 10y agoOn mobile that's a big deal. But on the other hand jQuery unlike MVC/virtualdom frameworks loads asynchronously and adds behaviour to static html ie it's non blocking.
- iSnow 10y agojQuery adds something like 20Kb to the whole site, that is nothing I see as a problem on mobile.
- BinaryIdiot 10y agoSo even with today's browser and JavaScript improvements that 20kb should still be avoided if possible. Why? - Each file downloaded adds latency. This especially hurts if you're on a satellite or similar, highly latent connection. The more files you have to download the worse start-up and various loading timing can get. - Okay, so let's say you minified and combined everything to help avoid the first issue, now you have a new issue: all JavaScript needs to get executed when included. So adding 20kb worth of JavaScript, while not all of it is executed immediately, a chunk of it is. This adds to start-up time. - Don't forget JavaScript execution, when compared to a desktop, is absolutely abysmal. For mobile web browsers you need to shave as much time off of start-up and ready states as possible.
- ge96 10y agoI wouldn't mind a smaller version of jQuery, I've heard of some, I've also tried min/slim versions. Still including a 200+kb file for jQuery... to just use well these are the most common ones I use: var targ = $("#targ"); targ.show,.hide,.val(),.text(),.css,.post(),.done,.promise(),.each(),.remove(),.on('blur" or .on({ blur: mouseup, .height(), .width(), .scrollTop(), etc... Probably much more, yeah certainly shorter code, gotten used to using it. edit: At this time I always build with jQuery, always include it in the <head> section. Could wait if it's a potential thing to slow down loading of site but I usually just have a copy on my server.
- iSnow 10y agoHm, over here, the 3.2-version of jQuery comes in as something like 85Kb, 323Kb when zipped. The slim build under 70Kb and compressed it's something like 20Kb. And there's zepto which comes in at around 10Kb.
- ge96 10y agoHaven't heard of Zepto. Will check that out. I realize too that ~70KB is not bad really. But I was working on a site for a client where their internet speed is 0.3Mbps and a ~300KB file was taking ~300ms+ to load. No maybe more than that actually(can't recall right now). 1KB files were taking a second to load. I don't know, had to figure out a closer data center and change the site a lot with how it loaded stuff.
- Jazcash 10y agoThe full version is 30KB after gzipping
- pluma 10y agoFWIW while gzipped sizes are more interesting for network performance, non-gzipped sizes give a better approximation for parsing times, which can be significant on low-powered mobile devices.
- dr_faustus 10y agoHell yeah, you do. I just recently had to create a tiny script (one of those notorious cookie warnings) without any dependencies. It's like pulling teeth. The DOM API is an ugly, verbose mess and its pretty unbareble to use without JQuery, zepto, etc.. Including the code for parsing cookies (yeah, you still have to do that, too) the script clocked in at 318 lines of code (without comments). With JQuery and the cookies plugin its would probably have been something like 30 lines. Thats 10 times the code you have to write, debug and maintain. So, of course, you don't NEED JQuery just like you don't NEED any means of transportation, you can walk everywhere after all. The question is, if you want to spend you whole life walking/writing verbose ugly JS code.
- akx 10y agoCurious: why'd you feel the need to write your own? https://cookieconsent.insites.com/demos/ https://cookieconsent.insites.com/demos/ is nice and light.
- nautical 10y agoInteresting .. https://github.com/js-cookie/js-cookie/blob/master/src/js.cookie.js https://github.com/js-cookie/js-cookie/blob/master/src/js.co... is under 165 lines with comments and provides a nice API on top .
- franciscop 10y agoYou also got my own cookies library https://github.com/franciscop/cookies.js https://github.com/franciscop/cookies.js at 107 lines (97 LoC), with the minified+gzipped version being 846 bytes. It can be easily copy/pasted into your code if you don't want the overhead of an extra request, or just using unpkg CDN: <script src="https://unpkg.com/cookiesjs@1"></script>
- lucideer 10y agoI'm sorry, I really hate to be condescending. I understand there are a range of levels of JS expertise out there, and using either jQuery or an appropriate library represents real value for many. However, when you're opening a comment with "Hell yeah, you do", I really have to respond. Hell no, you don't. If you're writing 318 lines of code just to do a cookie warning, that's fine. But please don't preach that it's necessary before actually learning some javascript. I'm also a bit baffled that it would take an entire 30 lines while using jQuery AND a cookie plugin. What are you doing to these cookies messages??? ::EDIT:: I have no idea if the code below works, and it could do with a lot of improvement (thinking about secure cookies, cookie paths, or even just using localStorage instead), but I can't imagine a bit of testing and revision of the code would balloon it to even twice its size. Least of all 30 times its size. (function() { var cookiesMessage = document.getElementById('cookies-message-wrap'); var cookiesAccept = document.getElementById('cookies-accept-button'); var checkCookies = function () { cookiesMessage.setAttribute('class', document.cookie.indexOf('cookiesaccepted=1')===-1?'':'accepted'); } cookiesAccept .addEventListener('click', function() { document.cookie = 'cookiesaccepted=1;expires=Tue, 19 Jan 2038 03:14:07 GMT;path=/'; checkCookies(); }); })(); What am I missing?
- fuhrysteve 10y agoWhile I don't agree that eliminating JQuery is necessarily something to strive for, I do like to see these sorts of projects because they help me learn how to reduce my dependency on jQuery when it makes sense to For example, there are new native language features in ES6 that make little utility functions like $.inArray obsolete.
- jorgeleo 10y agoI am sorry, this just does not make sense. It claims that because there is direct access to all the DOM API, you really don't need jQuery, but then it gives examples on how simple jQuery calls maps to different, multimethod calls to the DOM API. Those examples show how jQuery provide a nice abstraction on top of the DOM. This article is like saying, we don't need high-level languages because we can all learn assembler.
- dullgiulio 10y agoExactly. As a person who doesn not usually write Javascript, this project looks like an involutary advertisement for jQuery. Half of the native solutions have bugs or no IE support. All are three or more times more tendious than jQuery. The adage in the other comments seem "but jQuery is a big dependency." Did we already forget the left_pad npm debacle? jQuery didn't break then.
- throwanem 10y agoIf you're doing a bunch of these things, jQuery makes sense. If you're doing one of them, just write it out and move on. Don't pull in a multi-kilobyte dependency for one thing that takes two minutes to write. What relevance has left-pad here?
- minikomi 10y agoA lot of the animation examples are actually quite different in subtle ways.. Eg. the fade out example using opacity with CSS animations - the element still remains in the DOM. https://jsfiddle.net/hbLebx2d/1/ https://jsfiddle.net/hbLebx2d/1/ Try quickly clicking the "Toggle" button too.
- lucideer 10y agoI think people are reading too much into the intent of this. "You Don't Need jQuery" is in no way the same as saying "Don't Use jQuery". jQuery is a convenient abstraction on more verbose DOM APIs. Using it makes development quicker and easier. Here is an educational article demonstrating what those DOM APIs look like to many who may have opted to take the quicker & easier route of learning jQuery without learning DOM.
- squeral 10y agoMy view on this is that if you are going to take advantage of the extended list of jQuery plugins out there then you should definitely use it. But if you are just using it to make your own changes to DOM then just use native JS.
- andrewclunn 10y agoThe only future proof form of web development is being able to write things natively. Everyone gets pissy when you show that maybe their preferred framework or library isn't needed because that means their way of doing things might be replaced. But native code doesn't give a damn.
- matthewmacleod 10y agoObviously you don't need jQuery, and twiddling in the DOM for an Angular app means you are doing something wrong. However, jQuery is still quite useful and I include it in most projects. It makes various tasks, like event handling, AJAX requests and minor DOM tweaks, quite a bit nicer. Zepto is a good alternative with an almost-compatible API (http://zeptojs.com http://zeptojs.com). I would rather generally that developers used these off-the-shelf tools instead of implementing possibly buggy versions of functions like `height()`!
- masklinn 10y agoThough I've been using it less and less with the rise and convenience of vdoms, I always found that the most useful and delightful bit of jQuery is its treatment of nodesets as proper ordered sets, and that many of its manipulatory methods properly work on sets.
- throwanem 10y ago[].slice.call on the result of querySelectorAll turns that NodeMap (NodeList? I forget) into a proper array, on which all of the language's sequence manipulatory methods work as they should. I don't know why that method doesn't just return an array to begin with, but this is how you get one from it.
- BinaryIdiot 10y ago> [].slice.call on the result of querySelectorAll turns that NodeMap (NodeList? I forget) into a proper array, on which all of the language's sequence manipulatory methods work as they should. While true it's important to remember this creates a new, shallow array copy. It's not something you'd want to call often. Also it may be better to use Array.prototype.slice.call instead to avoid the extra, empty array instance your shortcut creates. How much better is likely insignificant, however; it's mostly a personal preference of mine :) > I don't know why that method doesn't just return an array to begin with, but this is how you get one from it. I believe this answers that pretty well (I've had the same, frustrating question in the past): http://stackoverflow.com/a/2601582/242023 http://stackoverflow.com/a/2601582/242023
- jwarren 10y agoI used http://youmightnotneedjquery.com/ http://youmightnotneedjquery.com/ a lot when I was trying to wean myself off mental jQuery dependencies. It's nice to know that there are some alternatives too. If you miss the $ function for DOM element selection, it's pretty trivial to wrap querySelectorAll in your own one-line helper function.
- iSnow 10y agoI don't quite understand why browser vendors haven't developed a terse, fluid API similar to jQuery/zepto with a touch of underscore/lodash and standardized on it. Not only would this be easier to code to, but the JS runtime should have some opportunities optimizing chained function calls to the DOM. 10y after release, jQuery is an established pseudo-standard that is not going away any time soon. Even with querySelector/querySelectorAll/getElementsByTagName/getElementsByClassName, I am still using jQ as the vanillaJs API feels so clunky and verbose.
- deleted 10y ago[deleted]
- vatotemking 10y agonot invented here syndrome, probably
- drawkbox 10y agoOne can drive automatic (jquery - no worry of browser issues) or stick shift (native - test in all browsers of all types for everything). In most cases you prefer automatic but sometimes you need stick shift when you go off-roading. If others have to drive, automatic is still probably better. When on a team it is good to use a common library that is tested across all browsers and does native calls encapsulated within it. When working on an app the last thing you usually want to get caught up on is browser inconsistencies that are easily avoidable, wasting time on that when not necessarily needed for that project. Other times you might need to go off-roading. If you always offroad though because you just hate automatic, well you won't be drinking coffee or using your phone much, you'll be worrying about shifting.
- exodust 10y agojQuery plugins have come to my rescue many times in tight production deadlines. The options out there, and generosity of developers to give away and keep updated in response to demands, is first class. jQuery by itself is something which is just nice to know is there, for quick DOM manipulation in the standard way you know how, and other devs know how. Hassle-free and accessible. As a jQuery fan I'm glad there's more tools and methods out there, however. I'm keen on VueJS myself but not yet confident. I'll be avoiding React and Angular because to me they feel like using an industrial lathe when all you need is a Dremel. Performance crumbling is still more likely to be caused not by choice of JS library, but shoving too much content down the throat of users because you as developer couldn't say no, or when you advised against it were ignored.
- err4nt 10y agoI love these sorts of comparisons. For years I was working with and around jQuery code and coders, and no matter how much I tired, I could just never learn jQuery. It felt too high level, like a world built out of train tracks, so instead of going directly from point A to point B you took the 'easy' route that quickly takes you from A to C with no traffic, how fast was that? To D, then D in such a simp,e and easy way. Then finally maybe end up at our destination. It wasn't until I resolved to try to learn JavaScript without jQuery at all that that mental barrier preventing me from understanding was removed. I blame the abstraction level and omnipresence of jQuery for preventing me from being able to learn JavaScript. Now Ive been writing vanilla JS for a couple of years, a, learning s lot, and I gain a lot of knowledge from posts like this, Ditching jQuery, and YouMightNotNeedJquery, not because I knew the jQuery way—just because they lay out the simple JS way to do common things. Long story short, after starting to learn JS I still cant figure out what a block of jQuery code is doing unless i re-implement it as vanilla to check and see if my guess is correct. I cant wait for the day when people are content with browser APIs for these things, many are simple but much more flexible.
- draw_down 10y agoBe careful- NodeList/HTMLCollection/etc are not Arrays! But, it's nice to make something dependency-free if you can.
- franciscop 10y agoA made a small experiment about this: https://superdom.site/ It's probably not for anyone to use it, but it was really fun exploring other possible APIs as alternatives to jQuery and with modern ES6+
- BuuQu9hu 10y agoThis is hilarious. I mean, relying on external libraries aside, just look at the readability and intuitiveness of the native syntax by comparison. It's not even close.