Calling a method on a jQuery collection

Neeraj Singh

By Neeraj Singh

on January 12, 2010

I was going through the Adding keyboard navigation and noticed that Remi replaced this code

1$(".coda-slider-wrapper ul a.current").parent().next().find("a").click();

with this code

1var direction = "next";
2$(".coda-slider-wrapper ul a.current").parent()[direction]().find("a").click();

I had never seen anything like that. In the above mentioned article, Remi used next and prev methods. However I wanted to know all the options I could pass since this feature is not very documented.

Snippet from jQuery source code

Here is code from jQuery that makes that above method work.

1jQuery.each(
2  {
3    parent: function (elem) {
4      return elem.parentNode;
5    },
6    parents: function (elem) {
7      return jQuery.dir(elem, "parentNode");
8    },
9    next: function (elem) {
10      return jQuery.nth(elem, 2, "nextSibling");
11    },
12    prev: function (elem) {
13      return jQuery.nth(elem, 2, "previousSibling");
14    },
15    nextAll: function (elem) {
16      return jQuery.dir(elem, "nextSibling");
17    },
18    prevAll: function (elem) {
19      return jQuery.dir(elem, "previousSibling");
20    },
21    siblings: function (elem) {
22      return jQuery.sibling(elem.parentNode.firstChild, elem);
23    },
24    children: function (elem) {
25      return jQuery.sibling(elem.firstChild);
26    },
27    contents: function (elem) {
28      return jQuery.nodeName(elem, "iframe")
29        ? elem.contentDocument || elem.contentWindow.document
30        : jQuery.makeArray(elem.childNodes);
31    },
32  },
33  function (name, fn) {
34    jQuery.fn[name] = function (selector) {
35      var ret = jQuery.map(this, fn);
36
37      if (selector && typeof selector == "string")
38        ret = jQuery.multiFilter(selector, ret);
39
40      return this.pushStack(jQuery.unique(ret), name, selector);
41    };
42  }
43);

As you can see, a variety of selectors can be passed to jQueryCollection[].

If you want to give a try, any jQuery enabled site should perform all of the below mentioned code without any problem.

1var a = $("a:first");
2var log = console.log;
3
4log(a["parent"]());
5log(a["parents"]());
6log(a["next"]());
7log(a["prev"]());
8log(a["nextAll"]());
9log(a["prevAll"]());
10log(a["siblings"]());
11log(a["children"]());
12log(a["contents"]());

If you liked this blog, you might also like the other blogs we have written. Check out the full archive.

Stay up to date with our blogs. Sign up for our newsletter.

We write about Ruby on Rails, React.js, React Native, remote work,open source, engineering & design.