
PlainJS – Vanilla JavaScript Repository - shakes
https://plainjs.com/
======
batat
Yea, let's bury jQuery again and make more "helpers.js" [1]

    
    
        export function extend(src) {
          var obj, args = arguments
          
          for (let i = 1; i < args.length; ++i) {
            if (obj = args[i]) {
              for (let key in obj) {
                // check if this property of the source object could be overridden
                if (isWritable(src, key))
                  src[key] = obj[key]
              }
            }
          }
         }
    

or just add super-unique stuff to our classes [2]

    
    
        DragSelect.prototype.removeClass = function( element, classname ) {    
          var cn = element.className;
          var rxp = new RegExp( classname + \'\\b\', \'g\' );
          cn = cn.replace( rxp, \'\' );
          element.className = cn;
          return element;    
        };
        
        DragSelect.prototype.hasClass = function( element, classname ) {    
          var cn = element.className;
          if( cn.indexOf( classname ) > -1 ) { return true; }
          else { return false; }    
        };
    

or write tons of boilerplate code like

    
    
        if (typeof element === 'string') {
            owner.element = document.querySelector(element);
        } else {
            owner.element = ((typeof element.length !== 'undefined') && element.length > 0) ? element[0] : element;
        }
    

(mmm, it's so vanilla)

[1]
[https://github.com/oncode/handorgel/blob/master/src/helpers....](https://github.com/oncode/handorgel/blob/master/src/helpers.js#L56)

[2]
[https://github.com/ThibaultJanBeyer/DragSelect/blob/master/s...](https://github.com/ThibaultJanBeyer/DragSelect/blob/master/src/DragSelect.js#L768)

~~~
twhb
Your JS knowledge appears to be severely outdated. Instead of the first you
can now write:

    
    
        Object.assign(target, object1, objectN);
    

The second:

    
    
        element.classList.add(className);
        element.classList.contains(className);
    

And the third has been fixed at a community level, as we've learned the value
of API strictness, obviating such checks.

I don't think anybody was against jQuery back when the alternative was helper
functions, I certainly wasn't. But that's five years ago at this point. Modern
JavaScript looks nothing like the code you posted, it's actually been built up
into a pretty good language.

~~~
csomar
You are ignoring browsers support. One of the main reasons I suggest using
jQuery is browser support. Another solution is to use a transpiler like Bable.

~~~
ctrl-j
> Another solution is to use a transpiler like Bable.

At this point in front-end development something like Babel is a must. If you
aren't using Babel/Flow/Typescript in your workflow, you are putting yourself
at disadvantage for no good reason.

For better or worse, transpiling is a fact of life.

~~~
platz
If you're not using a framework that requires you to transpile, jQuery
basically takes care of the most common bits.

------
91bananas
I still think jQuery/UI, libs maintained by a _group_ that has a vision,
organization, etc. Is a better solution than pulling in a ton of shitty half
hearted components, functions, what have you from a bunch of random developers
and repos scattered across the internet. Bootstrap works because it is built
by a team, solves a specific problem and solves it well. jQuery is the same
thing.

I grant that the things linked from this site are useful and novel, but I
don't want to build a project sourcing things from 16 different developers
when I could just bring in one library that does all of them, and might weigh
a little more over the net.

~~~
hw
Bootstrap at least provides a way to pull in only components that you need. I
would argue for a more modular jQuery.

There are some projects that don't require all that jQuery provides, and
sometimes you want to min-max performance and size of JS that gets downloaded.

Keep in mind that jQuery is maintained and contributed to by more than 16
developers so you are technically sourcing things from multiple developers,
just so happens they are in a single library.

Again, it really depends on what you're doing with your project and what you
need for your project. Most developers include jQuery by default because it's
just the most common and most used library, and PlainJS offers an alternative
which I think is great.

~~~
currysausage
What I'm looking for: libraries instead of one-size-fits-all frameworks.
Libraries annotated for Closure Compiler's advanced compilation mode, so I can
automatically tree-shake all the code that I don't need.

------
tomcam
Most cool! A couple notes.

Anyone maintaining a public-facing codebase should note that "All functions
work properly in IE 9 and above - most of them are compatible with IE 8."
jQuery has compatibility going back much, much further. Users in third world
countries with older computers are better served by jQuery.

jQuery has an enormous test suite, tons of documentation with examples, and
unparalleled third-party support.

------
disconnected
This is cute and all, but JQuery is slightly more than just a framework for
accessing the DOM.

My JS is a bit rusty, but I remember that in JQuery I could do:

$("some selector").do_things()

And "do_things" would be done on all matching elements. For example:

$("li").addClass("foo")

Would add the class "foo" to all "li". I could further refine the selector
above to select only the "li"s I wanted of course.

With the "plain js" solution, you have to "querySelectorAll" and then iterate
over each element.

Another example is "ajax" requests. In JQuery you have the general purpose
"ajax" method, with simple "success" and "failure" callbacks, and
configuration done via a standard JS object filled with all the necessary
parameters (and this object could be reused for the most part, since most of
the parameters don't change). You can also chain ajax requests together with
deferred objects. Simple, straightforward and useful.

With their proposed solution here, you have to faff around with the
XMLHttpRequest object every single time you want to make a POST or a GET. Ugh.
And if you need to chain a bunch of those together? Uuuuugh.

Yeah, you can put all of these things inside helper functions to hide the
ugliness, but if you are going through all that trouble, you are essentially
rewriting JQuery (or similar libraries), badly. If it is a one off thing, I
guess you don't need JQuery, but if you are rewriting most of these methods,
you are crazy. Use a library, and trim it down to remove the stuff you don't
need (JQuery allows this, IIRC).

A final aside. One oft overlooked advantage of JQuery is that the "$()" method
can be applied to anything, not just the DOM. You can create a JQuery object
that encapsulates, say, an array. Then you can iterate with "each", you can
"filter", etc. Also, you can easily trigger events on your objects with
"trigger" that other interested parties can listen to them by setting up event
listener with "on". Useful to give your classes some Qt style signal/slot
semantics.

~~~
mark242
The sizzle library that jQuery uses takes advantage of querySelectorAll.

[https://github.com/jquery/jquery/blob/2d4f53416e5f74fa98e0c1...](https://github.com/jquery/jquery/blob/2d4f53416e5f74fa98e0c1d66b6f3c285a12f0ce/external/sizzle/dist/sizzle.js#L293)

...only with a ton of wrapper code around it in order to support IE9 and
below. If you don't have to support ancient browsers, there's no reason you
can't write QSA code.

var nodes = document.querySelectorAll("li"); for(var i=0; i<nodes.length; i++)
{ nodes[i].classList.add("foo"); }

Yes it's slightly more code. It's also going to run a hell of a lot faster on,
eg, a mobile device.

~~~
megous
I prefer:

    
    
        for (let node of document.querySelectorAll("li"))
            node.classList.add('foo');
    

or:

    
    
        Array.from(document.querySelectorAll("li")).forEach(node => node.classList.add('foo'))
    

And if any particular pattern repeats in the code I'm writing I'll just create
a helper function for that pattern (most of the time locally). Like:

    
    
        let qsa => s => Array.from(document.querySelectorAll(s));
    

There's nothing to test about that.

~~~
loganfsmyth
You don't even need the `Array.from` anymore. `.forEach` on `NodeList` is
standard [https://developer.mozilla.org/en-
US/docs/Web/API/NodeList/fo...](https://developer.mozilla.org/en-
US/docs/Web/API/NodeList/forEach), so all you need to do is load a polyfill
for that.

~~~
Flenser
You might want to do map or filter before you do forEach. In which case you
would need to convert it to an array.

------
AndyKelley
If you don't have VanillaJS you can get it here: [http://vanilla-
js.com](http://vanilla-js.com)

~~~
beager
My problem with VanillaJS is that browser companies ship browsers with
VanillaJS support already. This is a clear case of picking winners, regardless
of VanillaJS's excellent benchmarks. Why should all these browsers ship with
Vanilla? Why not Vue? Why not MooTools? Why not Moo.fx?

~~~
dualogy
Not sure Vue falls in the same category, Vanilla lists "features" such as:
"DOM (Traversal / Selectors), Prototype-based Object System, AJAX, Animations,
Event System, Regular Expressions, Functions as first-class objects, Closures,
Math Library, Array Library, String Library". Not "component-markup-to-JS
transpilation" or SPA v-dom render loop

~~~
beager
Maybe there should be a Vue+MooTools library called VueTools.

------
gizmodo59
jQuery has helped me tremendously in the past and continues to do so. Not
everyone has to design a website like google.com and not everyone needs to
take into consideration every byte that is loaded in a web page. A library
that gives you a single way to do things that many browsers support in a less
verbose form is just amazing tbh.

At the end of the day when you need to just get things done jQuery still
shines. Does it produce spaghetti code? No, you are doing it. Does it become
an enabler in spaghetti code? Yes. But not all the use cases are the same.

------
olavgg
At my company we prefer using vanilla Javascript over all these (exhausting)
frameworks! Especially many of the new features in Ecmascript 6 makes things
much simpler. No more overusing bind(), template literals for building HTML
and so on.

Recently I've missed the way you create DOM elements like you do with
React.DOM so I created a simple proxy function like this:

let bai = {};

bai.DOM = function(){

    
    
        return new Proxy({}, {
    
            get: function(target, name){
    
                return function(args, body) {
    
                    let newEle = document.createElement(name);
    
                    if(args){
                        let keys = Object.keys(args);
                        for (let i = 0; i < keys.length; i++) {
                            newEle.setAttribute(keys[i], args[keys[i]]);
                        }
                    }
    
                    if(body){
                        if(typeof body === 'string'){
                            newEle.textContent = body;
                        } else {
                            newEle.appendChild(body);
                        }
                    }
                    return newEle;
                }
            }
        })

}();

With this you can create new DOM elements as following,

document.body.appendChild(

    
    
        bai.DOM.div(
    
            {"id": "message"}, 
    
            bai.DOM.p(null, "hello world")
    
        )

);

------
g00gler
jQuery is really useful when it comes to DOM manipulation, obviously.

Without using any framework you'll find yourself iterating over NodeLists all
over the place.

ie, it's much cleaner to write

$('p').css('color', 'blue');

Than

document.querySelectorAll('p').forEach(el => el.style.color = 'blue');

Also, Microsoft kinda screwed us by keeping IE 11 around until 2025.

~~~
megous
You can create a trivial helper function such as:

    
    
        let $ = s => document.querySelectorAll(s);
    

And then use:

    
    
        for (let p of $('p'))
           p.style.color = 'blue';
    

And if you start doing anything more complex per iteration:

    
    
        $('p')
             .css('color', 'blue')
             .addClass('bla')
             .filter(function() { $(this).parent().is('article'); })
                  .removeClass('qwe');
    

The code becomes much less magical and clearer (it's almost self explanatory):

    
    
        for (let p of $('p')) {
           p.style.color = 'blue';
           p.classList.add('ble');
           if (p.parentNode.matches('article'))
               p.classList.remove('qwe');
        }
    

Also much more debuggable in a debugger, and faster, as you're iterating only
once and are not calling many needless functions.

~~~
g00gler
Very true, nice codes :). Would be nice if we could write that without
transpiling.

------
throw2016
There is an unfortunate trend of people running down jQuery indiscriminately.

Given millions of people used jQuery for years without issue it's difficult to
believe those who benefited are going to run it down publicly because they
found something better.

The only people who would do this are those marketing something else. This is
by far the worst part of tech forums, this kind of insidious marketing that
seeks to 'force obsolence' on software and entire groups of people happily
using it because some are promoting their own thing.

------
austincheney
Or... just learn the DOM api. It is only about 2 hours of practice and study:
[http://prettydiff.com/guide/unrelated_dom.xhtml](http://prettydiff.com/guide/unrelated_dom.xhtml)

~~~
allover
jQuery is more than the DOM api.

------
cuu508
I've found [http://microjs.com/](http://microjs.com/) useful quite a few
times.

------
mike-cardwell
It took me less than 10 seconds to find an XSS on this website. Literally, the
first place anybody would look worked.

------
atonse
This is such a great idea.

I have been a web developer for 18 years, and kicking the jQuery habit has
been one of the toughest.

Frameworks also still rely on them. I'm a full time ember developer and last I
checked they're trying pretty hard to drop the jQuery limitation (REALLY sorry
to Ember devs if my info is outdated on this), but the ecosystem of ember/non-
ember addons surrounding it will prolong things even longer I'm sure.

------
projectramo
It is late in the day to try to replace jQuery. Does PlainJS have components?
Does it have bootstrap like functionality (i.e. columns)?

~~~
didgeoridoo
[https://en.m.wikipedia.org/wiki/Poe's_law](https://en.m.wikipedia.org/wiki/Poe's_law)

------
temporallobe
I'm so tired of this argument. There's no reason to drop jQuery for any of the
reasons stated. Especially with modern JavaScript engines, the performance hit
is negligible. Also, jQuery is especially optimized for complex DOM
manipulation which Vanilla JS cannot do on its own. Sorry, but
querySelectorAll is not the same as jQuery's powerful selector engine, and you
can't chain thngs the same way either. Sure, it's less relevant now than it
once was and for minor projects you could probably get away with a no-library
approach, but who are we kidding here? Most modern web apps and sites are
extremely library and framework heavy. It's complete bullshit to say
otherwise. The only exception is of course for design-centric, static content
web sites which tend to heavily lean on CSS for display logic. This article is
just full of amateur and meaningless advice.

------
tomxor
As someone who's written a lot of DOM code, i've tried dropping jquery (and
do) but selectively. You cannot drop it completely without great pain.

It's true that the DOM interface has stabilised and is now mostly consistent
cross browser, however the API is massively unwieldy in places, from
excessively long method names to irritating asymmetric potholes.

TLDR; Jquery is not needed for cross browser now, it's needed to make using
the DOM API not so ridiculously verbose and long winded. You need to use
jQuery today because: you want your DOM code to be 1/5th the size, more
legible, more debug-able.

I still use native methods where possible where there is little difference,
especially when performance is a concern.

------
javascriptChris
I agree jQuery isn't really needed but at the same time it's simpler for
people who may not understand JavaScript fully of willing to look at boring
web API docs to replicate some of the functionality.

------
fiatjaf
See also [https://svelte.technology/](https://svelte.technology/), the magical
disappearing UI framework.

------
EGreg
Can someone make a lite version of jQuery?

Angular did that.

I think Zepto was that for a while.

Isn't jQuery's lite version already there, which drops Android support etc.

Why not serve that to correct browsers?

~~~
52-6F-62
Why not try rolling your own?

* [http://projects.jga.me/jquery-builder/](http://projects.jga.me/jquery-builder/)

* [https://www.ericponto.com/blog/2014/10/05/es6-dom-library/](https://www.ericponto.com/blog/2014/10/05/es6-dom-library/)

~~~
rhizome
How do I get jQ without <IE9 support?

~~~
52-6F-62
Can't help you there specifically. However, depending on what you need from
jQuery, you might consider writing your own DOM library so you can have some
control over the size. If you have a look at some of the comments above,
you'll see that many jQuery advantages are met with equivalent features in
vanilla JS, just slightly more verbose. It isn't difficult to write a wrapper
for some of the major jQuery features. That second link is a terse example of
this.

------
futurefriendly
Read this thread but replace every mention of jQuery with "table layouts", the
parallels are striking.

jQuery has been a good friend for many years. It saved us from the drudgery of
cross-browser support and gave us an enjoyable API for browser development.

Technology moves on, today's browser APIs and tooling are light years ahead of
what we had 11 years. You might not need jQuery, and that's ok!

------
talindras
This is just a fork of [http://vanilla-js.com/](http://vanilla-js.com/)

------
alistproducer2
I went to the site and I'm a little unclear of what its purpose is. Is it
supposed to be a way to learn vanilla JS?

------
emodendroket
I mean when does it stop being "vanilla"? jQuery is written in "vanilla JS"
too.

~~~
Spivak
Completely counter to the author I would say everything is vanilla until you
start compiling and pollyfilling. Once you start writing in idealized
languages like TypeScript, CoffeeScript, or ES6 you're no longer writing
vanilla JS.

~~~
emodendroket
I could see that, or else maybe it's not "vanilla" if you start using
something like angularjs which expects to mediate basically the entire
lifecycle of your application. But I think in general the concept is ill
defined.

------
tareqak
Are there any kinds of dead code elimination tools for JavaScript? If <link>
tags can take additional attributes / query string parameters, the CDN be
smart enough to only send down the required code.

------
stevebmark
Can you imagine any other language / ecosystem where you're encouraged NOT to
use any libraries of any kind? The web is a weird place.

------
manigandham
jQuery usually falls back to native methods if the browser supports it. Also
build systems can easily remove unused code (webpack + babel-minify does great
with ES6 on the whole bundle), and you can even pick and choose the exact
components you need from the jQuery npm package.

------
ausjke
the issue is that I need bootstrap which requires jquery

------
sAbakumoff
jQuery is here to stay. It will outlive react angular vue and whatever shiny
framework you have been using.

------
woah
With this article and these comments, I feel like I've been transported back
in time 3-4 years.

------
MentallyRetired
DHTML, the framework!

------
jordache
who still uses jquery? to create usability mockups?

~~~
nextlevelwizard
Single reason why I should not use it?

~~~
dmitriid
Simple: You don't need React/Vue/Polymer for everything.

Personal anecdotal evidence: helping a friend create a very simple dashboard
of running jobs returned by a REST service + stats returned by the same
service etc. I've yet to find a reason to use jQuery, much less a bigger
framework.

~~~
jordache
>much less a bigger framework

So do you primarily write server side web apps? Anything slightly more
sophisticated on the front-end beyond imperative jQuery calls, requires a
framework, to organize your logic, and to scale up to a team level where
multiple devs can contribute to the same front-end codebase.

~~~
dmitriid
Nope. I'm a frontend developer :)

> Anything slightly more sophisticated on the front-end beyond imperative
> jQuery calls, requires a framework, to organize your logic, and to scale up
> to a team level where multiple devs can contribute to the same front-end
> codebase.

Yes. Often though, not a framework, but a library.

------
beager
I think it's a pretty amusing observation about the JS dev community to see
some of the responses to this here. Some people are here for Irony Club, some
people have no clue there's an Irony Club meeting, and some people are opening
up their jQuery wounds and bleeding all over the room.

One thing I'll say about jQuery vs doing POJS (Plain-ol' JavaScript,
pronounced _Poise_ , heh) is that jQuery comes from a world where browsers
sucked and build processes for JS were virtually non-existent. The market
share of sucky browsers is much smaller now, and we have sophisticated build
systems for JS. All of the benefits of jQuery (normalization, removing
boilerplate, etc) can be had with vanilla plugins that you can put in your
project and forget about.

The lingering damage of jQuery is that we have a bunch of jQuery devs in the
world now who simply cannot write JavaScript. We've got to move past that.

~~~
allover
> We've got to move past that.

No, we've got to move past lazy generalizations.

You've boiled down multiple issues to 'people only know jQuery'. Meanwhile the
rest of this thread is dealing with more interesting and accurate specifics.

~~~
beager
I have not boiled down multiple issues to that, I'm indicating that the
problem with jQuery in long-term adoption is that patterns meant to help devs
avoid the untenable realm of JS yesterday keep them sheltered from good JS
practice today. For that reason, we should move past jquery.

~~~
goatlover
"We" should do whatever makes sense for the project at hand, be that vanilla,
jquery, react, etc. There's a ton of different websites out there. jQuery
might be a requirement of the codebase, or already loaded, or heavily used,
etc. Or the developer might find it fastest to just drop jquery in for a
simple site.

