Banchan Kiro Banchan Kiro - 5 months ago 11
jQuery Question

jQuery (advanced?) function

I have found many example jQuery code where they use multiple functions like

$('object').function1().function2()

Can someone please explain to me how this actually works and how to properly use it?

Answer

Assuming jQuery, $(selector) returns a jQuery collection object. jQuery defines many methods on jQuery collection object, such as attr, find, css or slideUp, which will commonly return a jQuery collection object (same or different). This is commonly called "method chaining". For example,

$('div').css('background-color', 'lime').after('<div>More</div>');
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>Test</div>

the first part, $('div'), returns a jQuery collection containing our single <div>; .css(...) will set its background and return the same collection; .after(...) will insert the new <div> after the first one and again return the same collection.

Comments