ModernDesigner
ModernDesigner

Reputation: 7707

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

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! :-)

Upvotes: 33

Views: 36629

Answers (2)

John Slegers
John Slegers

Reputation: 47081

About a decade ago the top browsers were IE6, Netscape 8 and Firefox 1.5. Back in those days, there were few cross-browser ways to select an element from the DOM besides Document.getElementById().

So, when jQuery was released back in 2006, it was pretty revolutionary. Back then, jQuery set the standard for how to easily select / change HTML elements and trigger events, because its flexibility and browser support were unprecedented.

Now, more than a decade later, a lot of features that made jQuery so popular have become included in the JavaScript standard. Instead of jQuery's $selection.on(), you can now use EventTarget.addEventListener(). Instead of jQuery's $(), you can now now use Document.querySelectorAll()... etc... which begs the question of why we should use jQuery at all. And indeed, people are increasingly wondering whether we should use jQuery at all. So, if you think you understand JavaScript well enough to do without jQuery, please do! Don't feel forced to use jQuery, just because so many others are doing it!

Anyway, to understand why jQuery is so popular, it's important to understand where we're coming from!

Upvotes: 15

Mr. Polywhirl
Mr. Polywhirl

Reputation: 48600

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>

Upvotes: 22

Related Questions