DEV Community

Javier Vidal
Javier Vidal

Posted on

document.getElementById vs jQuery ID selector

document.getElementById and jQuery ID selector are not equivalent.

var element = document.getElementById('id');
Enter fullscreen mode Exit fullscreen mode

returns an HTML DOM Object, and

var element = $('#id');
Enter fullscreen mode Exit fullscreen mode

returns a jQuery Object. In jQuery, to get the same result as document.getElementById we can do:

var element = $('#id')[0];
Enter fullscreen mode Exit fullscreen mode

Top comments (3)

Collapse
 
bretgeek profile image
bretgeek

You can do this in a few different ways in YumJS too.

One of the easiest is getting the first of a class:


// Get first one

let button = yum('.button').first;

// Get the entire collection with the underscore

let buttons = yum('.button')._; 


// Use the variable reference you just made

yum(buttons).text('We are buttons');

Enter fullscreen mode Exit fullscreen mode

Aside from a the familiar chainable syntax, YumJS is very different than JQuery.

It doesn't replicate all of JQuery's functions but it does do other things that JQuery doesn't do with regard to reactivity and an optional component style syntax both of which can be mixed!

YumJS is also super small too. So...if you are still using JQuery give YumJS a try.

Check out my introductory article here on Dev.to dev.to/bretgeek/introducing-yumjs-...

Collapse
 
gotheer profile image
gotheer

We don't need jQuery any more.

Collapse
 
theonlybeardedbeast profile image
TheOnlyBeardedBeast

If you add an id to something, js creates an accessible variable with the same name, thats why yo shouldnt add the same id to multiple elements.