
From jQuery to JavaScript and back again - benhowdle89
http://benhowdle.im/2012/10/30/from-jquery-to-javascript-and-back-again/
======
macavity23
The core jQuery idea - using CSS selectors to find DOM elements and then
changing their properties and firing/monitoring events - fits so naturally
with the HTML/CSS model that it feels like it should be part of the standard
DOM API.

I'm not aware of any JS.next-type efforts to do this though :(

~~~
jacobr
To just make the DOM API's a little cleaner is so simple in a language like
JavaScript, why not just create the abstractions as you need them?

This is not something you should use in production, but just a quick example:

    
    
        function setAttr (attr, val) {
          return function (elem) { elem.setAttribute(attr, val); };
        }
        NodeList.prototype.forEach = Array.prototype.forEach;
        var $ = document.querySelectorAll.bind(document);
    
        $('.foo').forEach(setAttr('foo', 'bar'));

~~~
masklinn
> This is not something you should use in production, but just a quick
> example:

Your quick example is risky and likely broken to all MSIE <= 8:
[https://developer.mozilla.org/en-
US/docs/DOM/NodeList#Why_ca...](https://developer.mozilla.org/en-
US/docs/DOM/NodeList#Why_cant_I_use_forEach_or_map_on_a_NodeList.3F)

~~~
mattmanser
There's no forEach in IE8.

------
rtpg
jQuery is more or less a wrapper for the DOM API. Considering the amount of
man-hours(1 guy over three weeks) that went into designing the DOM, it's safe
to assume that jQuery does the interfacing better.

I don't understand why people want to make a distinction between vanilla JS
and jQuery. It's like saying you want to make a distinction between standard
C++ and QT. One is a language, the other is an interface. jQuery doesn't
exactly provide a standard library by any stretch of the imagination.

~~~
CWIZO
The problem is that many many "developers" think that jQuery is a language.
Just browse stack overflow and you'll see. This "developers" couldn't get a
element from the DOM with JavaScript if you threw document.getElementById in
their face.

So that's the point that OP is making. First learn JavaScript, then move to
abstractions such as jQuery. That way you won't ask silly questions such as
"how to write a if statement in jQuery".

~~~
benhowdle89
This. Everything this. Find the pain points with JavaScript, then make your
life easier with jQuery.

~~~
PommeDeTerre
Just about everything is a pain point when using JavaScript or when dealing
with the DOM. So it's understandable, although maybe not a good idea, why so
many people don't separate JavaScript and libraries like jQuery, MooToo, or
YUI.

Such a combination is essentially needed merely to bring JavaScript up to a
minimal level of usability. We generally don't find this to be the case with
other, more sensible languages, which is why it seems so odd. C, C++, Java, C#
and Python implementations come with a sensible language and a rich standard
library. Developers using them don't need to bring their own standard library
just to get a basic level of functionality.

~~~
masklinn
> C++ [...] implementations come with a sensible language and a rich standard
> library.

You shouldn't make your trolling so obvious, man.

~~~
jeswin
After reading parent, I've decided to use Java for all DOM manipulation.

------
mattangriffel
"My only piece of advice is to get a solid background in JavaScript, then move
forward, appreciate the blood, sweat and tears Resig put into jQuery"

I hear this point made a lot, for example in reference to learning Ruby before
Rails or C before Ruby, but I don't think it's right. They used to teach kids
Latin before Spanish or French (in the 1700s):

"We are told that it is proper to begin first with the Latin, and having
acquir'd that, it will be more easy to attain those modern languages which are
deriv'd from it" (quote from Ben Franklin's autobiography)

But that's silly and no one does this anymore because LATIN SUCKS and it's
harder to learn Latin than any other language. jQuery is easier to learn than
JavaScript. Why not start with jQuery and then learn JavaScript after?

~~~
vanderZwan
That analogy doesn't really hold, because Spanish and French do not run on
Latin under the hood, so they don't hide away the complexities or any errors
you might be making while using those languages.

On the other hand, it's quite a reasonable assumption that getting a good
understanding of JavaScript gives a broader context of what is going on that
is necessary to properly use jQuery.

~~~
mattangriffel
First, Spanish, French, and other romance languages are derived from Latin,
and so the thinking was exactly that. Learn Latin and you'll have a better
understanding of what's going on.

Second, the argument that language X runs language Y under the hood so you
should learn Y in order to get a good understanding of X doesn't hold.
JavaScript is written in C++ in most cases, which compiles into assembly. So
why not learn assembly to get a better understanding of JavaScript?

That's silly.

~~~
ditonal
There are big differences between a language being derived from another
language, having it's interpreter written in another language, and actually
being a framework written in the same language. Your "Don't learn Latin before
French" analogy makes sense for those claiming you should learn C before Ruby.
But jQuery doesn't derive from Javascript, it's a framework written in
Javascript. If you write jQuery, you will run into Javascript issues, because
you are writing Javascript. Even if you could make the argument it's a similar
philosophical idea, anybody with experience will know in practice that a
jQuery coder will run into Javascript issues much, much more frequently than a
C++ or assembly issue. The leap is much, much smaller. The best analogy I can
think of along the human language lines is instead of a French student
learning Latin, it would be a student of business French being encouraged to
better understand all of spoken French.

With all that said, I also lean towards "just learn what you want or need to
know" train of thought. I think those of us who enjoy learning what's under
the hood overestimate it's necessity for "getting things done". I don't think
there's anything wrong with learning and using jQuery without diving into the
messier details of vanilla Javascript unless necessary. Also, for many of us,
those ugly situations when we are forced to figure out what's going on behind
the scenes is when we actually understand it anyway.

------
gmac
Can you do X smaller and faster without jQuery?

If X is non-trivial and you need to support old/crappy browsers, then probably
not (well, not without person-years of pain).

Conversely, if you can get away with targeting only IE9+, WebKit and Mozilla,
or if X is dead simple, then almost certainly yes. And you should try it, too,
because jQuery is a big warty kitchen-sink of a framework. In those cases
these days I use CoffeeScript and a few simple homegrown helpers[1].

[1] <https://github.com/jawj/affogato>

~~~
masklinn
> Conversely, if you can get away with targeting only IE9+, WebKit and
> Mozilla, or if X is dead simple, then almost certainly yes.

Faster maybe, but smaller probably not unless you rebuild half the jquery
interface on top of straight DOM (and in that case, why not use zepto or some
other similar library?)

Every time I try to go with straight DOM, it turns out to be a pain because
the DOM interface as a swamp of javaisms unfit for human usage.

~~~
gmac
You certainly can go smaller if your needs aren't hugely complex. I have a
'make' function for creating and appending to the DOM, 'get' for retrieving,
and 'cls' for className-wrangling. See for example here (in CoffeeScript,
which makes Object arguments seem terribly natural):

[https://github.com/jawj/github-widget/blob/master/github-
wid...](https://github.com/jawj/github-widget/blob/master/github-
widget.coffee)

------
crazygringo
> _The reason being is that it abstracts out a lot of the JavaScript “gotchas”
> into nice, easy function calls. Most errors are caught by jQuery and never
> seen by the user, but more dangerously, never seen by the developer._

I have no idea what he's talking about. jQuery normalizes browser differences,
but what on earth kinds of "errors" are "caught" by jQuery, that are
"dangerous" to hide from the developer? I mean, I've used jQuery on projects
for years, and I can't even imagine.

~~~
joshuahedlund
A lot of javascript causes errors if you try to do stuff on non-existent
elements:

> document.getElementById("nonexistent").innerHTML = "";

This however will not cause any errors, it just won't do anything:

> $("#nonexistent").html("");

These sort of do-nothing-but-don't-throw-an-error responses can encourage
developers to be less careful about making sure elements exist as they are
expected, etc.

~~~
camus
since $("foo") returns a jQuery object that has a method html then it is valid
, like [].forEach(myFunc) is valid: a empty array is not an error. there may
be other relevant cases but i dont think this one is.

~~~
joshuahedlund
That's precisely my point. To put it another way, jQuery converts what would
be a javascript error into a technically "valid" empty array. Sometimes this
is useful, but it can also help mask poor logic.

~~~
camus
I doing agree, it is not a javascript error ! again if i take the array
exemple and the following code :

    
    
        var a = [1,2,3,4]
        // now i filter the array
        var b = a.filter(function(a){return a<0} );
        // b = []
        // now do something on b
        b.forEach(function(e){console.log(e)})
        // will "fail" silently , because it will output nothing
    

is what i'm doing stupid ? yes, but it is 100% valid from a javascript
perspective. It is a coding error , but not a JS error.

------
thomseddon
Using the collective knowledge and testing that has been used to derive the
methods in jQuery is hugely attractive, grappling with cross browser issues
every time you want to achieve something would be utterly pointless.

Despite this, every time I start a new project that requires some DOM
manipulation etc I lament at having to include the entire library just to
harness a tiny aspect of it's power.

A delightful solution to this would be a similar degree of modularity as there
is in, for example, jQueyr UI. I know there is a degree of modularity
(<https://github.com/jquery/jquery#modules-new-in-18>) but this is reasonably
high level and at this level the argument of using google's CDN and so
encouraging a cache hit is still very strong. If you could strip both jQuery
core and shizzle (I rarely/never use attribute selectors for example) right
down to a hundred lines of so of what you really needed, this would be very
very compelling.

I had a relatively brief investigation into the codebase a while ago with a
view to how hard this would be to implement but didn't really have the time to
follow it through. My conclusion was that it wouldn't be easy, anyone have any
ideas/thoughts on this?

~~~
dmethvin
> A delightful solution to this would be a similar degree of modularity as
> there is in, for example, jQuery UI

Except that jQuery Core is a completely different thing. You _know_ if you're
using jQuery UI Menu but not jQuery UI Dialog so you can decide to include
them or not with a custom web-based builder just by clicking boxes.

The jQuery Core features used by all the plugins you collected to build your
site are not immediately obvious. Did they use .replaceWith() for example, is
it safe to leave that out? What about .load(), did they use that API? Oh,
wait, there are two different things that .load() does, one is AJAX-y and one
is event-y, if they did use it which one did they mean?

By having the full library there you don't need to spend lots of time tracing
down these dependencies. And in JavaScript these are all dynamic, you can
never really be sure you got the dependencies right until you find out you
didn't.

That's why I strongly advocate that the average programmer should just use the
whole standard jQuery core library unless you are in some spot where saving
10-20KB gzipped is so important that you're willing to chase down those
dependencies yourself.

~~~
thomseddon
If your point is "if you aren't able resolve the dependencies in the code you
include, then don't try" then I suppose I agree.

Frankly with the amount of plugins I usually use (0-2) this isn't really
problem...

The point is, there are some great features and fixes tucked away in there and
sometimes I only want say <5-10% of the library, I could write it myself but
then I loose all the collective knowledge embroiled throughout.

------
timinman
My evolution as a JavaScript Developer:

1\. I found out I could use Rails helpers to make really cool stuff. It
generated ugly JavaScript code and errors that no one could see. No one got
hurt. Win.

2\. I realized I could use Prototype.js directly. The code was still ugly, but
I could do even more. I eventually switched to jQuery because of the large
ecosystem.

3\. I started buying and borrowing JavaScript books. I decided to use vanilla
JavaScript. I realized that it was a pointless exercise because of browser
incompatabilities: <http://www.quirksmode.org/dom/w3c_core.html>. Now I
understand JavaScript, but use jQuery to interact with the DOM.

It's probably impractical to suggest people learn vanilla JavaScript first.
People who find jQuery are going to use and love it. They are going to write
ugly code, but they will actually be able to accomplish something. As time
wears on, they will learn the finer points of the language.

------
bpatrianakos
Great points and definitely something a lot of developers have started waking
up to recently. I could be way off base, but I kind of think that jQuery is to
client-size coding what PHP is to backend coding (yes I know there aren't any
other client-side languages but just follow me here for a sec). They can be
used well in the hands of a competent programmer but they will absolutely let
you write god-awful code, never complain, and let you think there's nothing
wrong with what you're doing.

In the end its just another case of knowing your tools and when to use 'em.

~~~
camus
A bad programmer will write bad code wether he uses jQuery or not. going pure
DOM doesnt make the code better, especially when dealing with browser
differences. if you have the time to re-implement all the abstraction needed
in order to make your code work on legacy browsers each time you code a DOM
related function , good for you , i dont.

the goal of jQuery is not to provide a MVC framework , an AMD framework , or
whatever that helps writing modular code. The goal of jQuery IS DOM
manipulation and having a single API for every browser out here. And jQuery is
a framework not a langage so your argument ( PHP==jQuery because it let's
developers write ugly stuff) doesnt stand.

------
fmsf
Just to leave here the same comment I left on the blog. I completly agree,
jQuery is an awesome tool. But developers need to learn how to write modular
javascript before they start hitting on frameworks that provide shortcuts. I
recently wrote a post about this issue. Mind if I share it? Feed back is
welcome. [http://franciscomsferreira.blogspot.com/2013/01/how-to-
write...](http://franciscomsferreira.blogspot.com/2013/01/how-to-write-
maintainable-javascript-or.html)

------
xentronium
There is actually more choice than jquery and vanilla javascript. Mootools,
for example, is a great toolkit that helps you build great abstractions.

~~~
emehrkay
Funny that you mention MooTools because his example of good jQuery is the
typical MooTools class.

------
loahou04
i definitely think frameworks are a huge help, however, i do believe that
understanding the underlying source of the frameworks will help you even more.
Use the framework as needed but truely understand why they chose the direction
they went with in the framework/toolkit in order to better yourself and grow
as a developer

------
camus
jQuery exists for one simple reason : deal with DOM inconsistencies between
browsers, and it works. Some people tested the code for you on all the browers
so you can assume your code will work on all the main browsers out there.

Those who think they are too smart to use it certainly are not real web-
developers in real businesses , having to support legacy browsers because
their client base still run on IE6. or they have enough time to work on all
the quirks of IE6 IE7 IE8 each time they write a DOM related function , i
dont...

jQuery is here for quick DOM manipulation, is basically a facade pattern, and
the bright idea was to use CSS selectors to query the dom.

jQuery selector engine is far more powerfull than document.querySelector

Why is it hard to work with the DOM ? because it is STRONGLY and staticaly
typed ! it has interfaces and type checking , so using it with a
dynamic/weakly typed language is hard. the DOM doesnt use duck typing , that's
why can get all these DOM ERROR , invalid DOM LEVEL call ,and you cant create
an Element or a Node without a factory etc ... and let's give credit to MS on
this, they created DHTML because they understood it made little sense using
that api with that language ( each time you are using innerHTML it is DHTML,
querySelector to until it was made a standard ).

yet I dont see people saying they are too smart to use DHTML because it is not
pure DOM. but do they really care about what interface is used ? how the
factory method build the given objects ? i dont think so.

~~~
masklinn
> jQuery exists for one simple reason : deal with DOM inconsistencies between
> browsers, and it works.

It exists for a second reason as well: make DOM interaction not suck. Because
they suck hard out of the box.

> Why is it hard to work with the DOM ? because it is STRONGLY and staticaly
> typed !

Not really. It's because it's defined through a very restrictive abstract
language which assumes almost nothing about the implementation language
(basically, that the implementation language has method calls and a name can
map to multiple arities somehow). That gives an API which can be implemented
on pretty much any object-oriented language, but will also suck on pretty much
all of then.

> querySelector to until it was made a standard

Uh... no it was not, if you want to give MS credit where credit is due you can
give them XMLHttpRequest, but definitely not querySelector which is a WhatWG
brainchild (the first revisions were by Anne van Kesteren and Lachlan Hunt).
MSIE didn't get querySelector until IE8 (March 2009), Webkit landed it in
December 2007 and Gecko in July 2008.

Also, innerHTML was standardized as part of the HTML5 effort, as well as a
number of ther "DHTML" features.

And while you give praise to MS, don't forget to criticize them for e.g. not
having implemented the DOM Events API until IE9.

