3 - difference between $() and document.getElementsByTagName()

jquery

#1

Can someone explain to me what's the difference between this piece of code:

$(document).ready(function() {
    var $target = document.getElementsByTagName("li")[4];
    $target.fadeOut('fast');
});

and

$(document).ready(function() {
    var $target = $("li:nth-child(4)");
    $target.fadeOut('fast');
});

Isn't basically the same thing? Why is the 1st not working?


#2

The above is vanilla JS. It does not return a jQuery object, only a JavaScript collection. I'm pretty certain that jQuery methods cannot be called on vanilla collections, so,

$target.fadeOut('fast');

might present a problem, and an error relating that $target does not have a property 'fadeOut'.

A jQuery collection is first of all, an instanced object of the jQuery function, so it has all of the jQuery.prototype object in its prototype, as well. That is what gives any object in the collection full access to the methods now associated with their instance.

$("li:nth-child(4)");

IS a jQuery object, a collection of all the nodes in the document that match the specifics of the selector. $target, then, will have all of jQuery at its disposal.


#3

Thanks for the help! :smile: