JavaScript's document.querySelector() same as jQuery $() method?

ModernDesigner picture ModernDesigner · Jan 2, 2013 · Viewed 34.6k times · Source

I have been wondering why people glorified jQuery's $(".myClass") method when JavaScript has a generic document.querySelector(). Is there something I'm missing here? Why not just use the document object?

I am completely new to JavaScript, so is there some type of con to document.querySelector() that I am not aware of?

I'd really like to know, because I ran across something like this earlier and I'm wondering if it might help a situation I'm in:

var retrieve = function( s ) {
    return document.querySelector( s );
};

retrieve(".myClass").style.display = "block";

Note

I have nothing against jQuery at all. In fact, I love it. However, I'd rather not cheat myself using the easy pre-made ready-to-use tools when I'm just now trying to learn JavaScript.

Any help would be much appreciated! :-)

Answer

Mr. Polywhirl picture Mr. Polywhirl · Jan 2, 2013

Cross-browser and legacy support.

You can also use getElementsByClassName() if you don't want to use Jquery. There is a response to a post on devshed by user: KorRedDevil that may be of interest to you.

I took your function from your post and made it return an array. After you have that array of elements, all you have to do is loop over them. You can try it out here.

Javascript:

var retrieve = function(className) {
    return document.getElementsByClassName(className);
};

var elements = retrieve('foo');
for (var i = 0; i < elements.length; i++)
    elements[i].style.background = '#dfd';

Markup:

<p class="foo">foo</p>
<p class="bar">bar</p>
<p class="foo">foo</p>
<p class="foo">foo</p>
<p class="bar">bar</p>
<p class="bar">bar</p>