Of these two, which is correct?
jQuery('someclass').click(function() {
alert("I've been clicked!");
});
or
jQuery('someclass').each().click(function() {
alert("I've been clicked!");
});
I’m wondering if I have a fundamental misunderstanding of how certain aspects of jQuery work, or if it’s just got a lot of tolerance built into each of its functions to allow either a single element or a collection of elements.
The first is correct, the second will fail as a callback function is not defined. If a callback function was defined and the click event handler applied to each iterated element inside of the callback in
.each(), then the two would be functionally similar. However, theeachcall would really be redundant as jQuery comands/methods are generally applied to all matched elements in the jQuery object (there are certain methods such as .val()that do not, but they are the exception than the norm). This is done by internally applying.each()🙂The jQuery object is an object with array-like properties; all matched elements are indexed properties of the object i.e.
where
[DOM Element]represents a reference to an HTMLElement in the DOM that matches the selector.The advantage of being array-like is that it makes performing array operations on the object very straightforward.