Search code examples
jquerymethodsundefined-behavior

jQuery .first() method returns a collection intead of the first element


Using the first() method on a collection of elements displays wierd behavior.

$("button.overlay").on("click",function(e){
    e.stopPropagation();
    let i = $(e.target).closest('.style-display').children('.modal-info-container');
    let k = i[0];
    let j = i.first();
});

To my understanding using [0] and .first() should give the same result. What happens is that .first() returns the unchanged collection instead. What am I doing wrong?


Solution

  • using [0] and .first() should give the same result

    No. This is not correct.

    $(selector).first() is the same as $(selector).eq(0)

    Both of these (.first/.eq) return a jquery collection.

    while

    $(selector)[0] is the same as $(selector).get(0) - See get() - which retrieves the DOM node instead of returning a jquery collection.


    .first() will return the "unchanged collection" if the original collection had only 1 element.

    Consider $("div").length vs $("div").first().length