6 ms·
You can basically sum up this entire rather ridiculous site with "Yes, you don't need jQuery, you can just use the built-in methods, but using jQuery is general
by bshimmin 12y ago
You can basically sum up this entire rather ridiculous site with "Yes, you don't need jQuery, you can just use the built-in methods, but using jQuery is generally more pleasant, more consistent, and involves less typing". One particularly egregious example from the site:
$('#foo').removeClass('bold');
vs.
document.getElementById('foo').className =
document.getElementById('foo').className.replace(/^bold$/, '');
The author summarises this, helpfully: "As usual, more characters, but still easy without jQuery."
Of course, if you were doing that remove class operation quite often, rather than writing all that code out each time, you might wrap it up in a helper method, and maybe you'd call it, I don't know, "removeClass" or something; perhaps if you were doing a whole bunch of DOM operations you might create little helper methods for each one, again to save you some typing. Pretty quickly you might end up with a little library of helper methods... and, of course, being a wonderful programmer who never makes mistakes, I'm sure that little library would be every bit as optimised, reliable, and correct as a battle-tested library used on hundreds of thousands of web sites.
- oneeyedpigeon 12y ago.classlist() [1] is coming [2]. It'll allow you to do: document.getElementById('foo').classList.remove("bold"); Sure, it's still more verbose. But a lot of what jQuery does is slowly being obsoleted by better native javascript apis. [1] https://developer.mozilla.org/en-US/docs/Web/API/Element.classList https://developer.mozilla.org/en-US/docs/Web/API/Element.cla... [2] http://caniuse.com/#feat=classlist http://caniuse.com/#feat=classlist
- jhpriestley 12y ago`$(".foo").removeClass("bold")` becomes the wonderfully concise [].map.call(document.querySelectorAll(".foo"), function(node) { node.classlist.remove("bold"); })
- sfeng 12y agoThis may seem anecdotal, but I can tell you from writing a lot of non-jQueryified code that with modern browsers, applying classes to dozens of elements dynamically can be an anti-pattern. 99% of the time, when doing something which previously would have required that, I can use a single class on a parent element.
- usingpond 12y agoNot if you're in an environment (like mobile) where you want to reduce repaint.
- malandrew 12y agoIn which case you don't want to be using jQuery at all and should instead be using a virtual DOM implementation like virtual-dom, famo.us, react or mithril. https://github.com/Matt-Esch/virtual-dom https://github.com/Matt-Esch/virtual-dom
- ulisesrmzroche 12y agoWhat if you don't have the option to all of a sudden bust out a new framework? Some of these scenarios are just unrealistic.
- ulisesrmzroche 12y agoNo, you're going to mess with repaints and renders. It is not an anti pattern.
- ahoge 12y agoWith spread and fat arrows: [...document.querySelectorAll('.foo')].forEach(node => node.classList.remove('bold'));
- eli 12y agoThe day I can drop support for IE <10 will be a good day.
- mcmillion 12y agoAnd in 5-10 years, we'll be able to use it.
- bshimmin 12y agoSure, the native APIs are slowly catching up, and classList is definitely a useful one. You'd better hope that there actually is an element with an ID of "foo", though, otherwise your example will throw an exception. The last time I pointed this out here, there was some disagreement as to whether jQuery's behaviour is actually desirable. I think it is, but I'm probably biased from writing too much jQuery over the years.
- Khao 12y agoSo when those new native api functions arrive, jQuery will start using them and gain some performance boost (using native vs. custom js code) while at the same time remaining backwards compatible (by doing feature detection). No one wants to write their own feature detection code so this whole page about using native apis is instead of jQuery is ridiculous. If the point of that website was to educate people on the apis that jQuery calls under the hood, it chose a really poor name.
- kyllo 12y agoExactly. "No one wants to write their own feature detection code" is the whole point of jQuery.
- rip747 12y agoYou hit the nail on the head.
- aplummer 12y agoThis a thousand times, I know with $.trim it will use trim() for good browsers and then whatever hack effort was necessary for IE8. It would be devastating to have to write this manually.
- malandrew 12y agoOr you could use the class list polyfill.
- organsnyder 12y agoIf that's all you need, then that would be fine. However, for most projects you end up needing many other such polyfills, to the point that you might as well use one library—jQuery—to provide them all (plus a lot of other functionality).
- taf2 12y agobefore jQuery I always defined an ID method like: function ID(id) { return document.getElementById(id); } saved some typing. I'll always try to use jQuery now though, bigger problems to solve.. few extra bytes to download is not that bad...
- deleted 12y ago[deleted]
- TheGunner 12y agoWhile I'm waiting for that, and still writing applications that have to support ancient versions of IE, I think I'll stick with Jquery. Can't wait for the future though
- pawelk 12y agodocument.getElementById('foo').classList.remove('bold'); see https://developer.mozilla.org/en-US/docs/Web/API/Element.classList https://developer.mozilla.org/en-US/docs/Web/API/Element.cla...
- prezjordan 12y agoOnly since IE10.
- ulisesrmzroche 12y agoIf I saw that, first comment on the PR would be to wrap that eye sore in a wrapper function with a clear name. Which is basically what jQuery is doing.
- masklinn 12y agoUnless it turns out there's no `foo` in the page, then that blows up.
- _delirium 12y agoI agree that's a lot nicer. But it also looks like essentially a mechanical transformation. Instead of a runtime library (whether jquery or roll-your-own), would it be possible to handle cases like that via syntactic sugar that expands at deployment time, and doesn't require shipping a library to the end-user's browser? (Or does something like that already exist? I haven't really spent any time with CoffeeScript and other compile-to-JS languages, so it's possible they already have nice syntax for this kind of thing.)
- Nullabillity 12y ago> Instead of a runtime library (whether jquery or roll-your-own), would it be possible to handle cases like that via syntactic sugar that expands at deployment time, and doesn't require shipping a library to the end-user's browser? You could, but that would require user-agent sniffing (and thus continuous maintenance), and would probably need a pretty unusual caching setup.
- nickdandakis 12y agoI honestly just called bullshit and stopped reading after the first example (selecting elements by id).
- shanemhansen 12y agoThe second function is broken for an element with multiple classes. DOM fail.
- voyou 12y agoThat makes the site a pretty good illustration of one of the reasons why, although you don't have to use jQuery, you maybe should. With jQuery you benefit from years of development and testing, which your own code probably hasn't undergone.
- spoiler 12y agoThis is why one writes unit tests, though. Although, I do occasionally use jQuery, I'm more comfortable and productive when not using it. Also, if I shamelessly take a peek at jQuery's source now-and-then to see how they implement certain features so I can make a helper for it.
- ggonweb 12y agoalso it hides the discrepancies between the various browsers
- mjt0229 12y agoThis is exactly the point. I don't mind the extra typing in those first few examples because jQuery is mysterious and it's nice to cut through the mystery. However, I don't want to have to fill my code with conditional logic based on the user's browser - that's lame. The real value of this site is not what it says, but rather a reminder that jQuery is an abstraction and is made of code rather than magick.
- ErnestedCode 12y agoIt's like saying "You don't need a web browser at all -- See how we can navigate the web using cURL!"
- walshemj 12y agoor you can use just what js you need instead of loading pages down with dozens of bloated js library's and wondering why your site sucks and is slow as a slow thing
- jbeja 12y agoActually since forever, you don't need to use document.getElementById("x") in any case. You just by putting the id to the element, it is already available to you referencing it by such id. So this: document.getElementById('foo').className = document.getElementById('foo').className.replace(/^bold$/, ''); Can become to this: foo.classList.remove("x"); And is miles away more performant than slow jQuery.
- dmethvin 12y agoThat won't work on Android 2.x, which doesn't support `.classList`. Performance isn't even an issue here since changing classes will cause a reapply-styles and layout.
- jbeja 12y agoI care as much for Android 2.x as ie below 10.
- mikeryan 12y agoNote the Jquery ticket for this issue can be tracked link below. In most cases Jquery will try to use to native implementations this is the ticket in this case they've never found it to be "miles away more performant". http://bugs.jquery.com/ticket/5087 http://bugs.jquery.com/ticket/5087
- jackmaney 12y agoPerhaps I'm being a bit dense (I've done prettymuch no front-end JavaScript), but since className gives a single string with class names separated by spaces[1], won't document.getElementById('foo').className = document.getElementById('foo').className.replace(/^bold$/, ''); fail if the element in question has more than one class? In that case, you'd need to get the className attribute, split it by spaces, do the replacement in the resulting array, and then join back and assign, I believe. [1]: https://developer.mozilla.org/en-US/docs/Web/API/Element.className https://developer.mozilla.org/en-US/docs/Web/API/Element.cla...
- sesutton 12y agoYou're right it will only work for one class. This is actually a perfect example of jQuery smoothing out the rough edges for you. I think the split method would work (provided you remember to split with \s instead of just space). It actually took me a while to come up with a regex replace that won't break in some corner cases ( I think) document.getElementById('foo').className = document.getElementById('foo').className.replace(/(\s|^)foo(\s|$)/, ' '); \b is out because it matches - and would kill stuff like foo-bar.
- cema 12y agoSubstitute \bbold\b for ^bold$ -- a potentially introduced extra space in the class name (string) should not matter.