Calling a method on a jQuery collection

Neeraj Singh

Neeraj Singh

January 12, 2010

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

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

with this code

var direction = "next";
$(".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.

jQuery.each(
  {
    parent: function (elem) {
      return elem.parentNode;
    },
    parents: function (elem) {
      return jQuery.dir(elem, "parentNode");
    },
    next: function (elem) {
      return jQuery.nth(elem, 2, "nextSibling");
    },
    prev: function (elem) {
      return jQuery.nth(elem, 2, "previousSibling");
    },
    nextAll: function (elem) {
      return jQuery.dir(elem, "nextSibling");
    },
    prevAll: function (elem) {
      return jQuery.dir(elem, "previousSibling");
    },
    siblings: function (elem) {
      return jQuery.sibling(elem.parentNode.firstChild, elem);
    },
    children: function (elem) {
      return jQuery.sibling(elem.firstChild);
    },
    contents: function (elem) {
      return jQuery.nodeName(elem, "iframe")
        ? elem.contentDocument || elem.contentWindow.document
        : jQuery.makeArray(elem.childNodes);
    },
  },
  function (name, fn) {
    jQuery.fn[name] = function (selector) {
      var ret = jQuery.map(this, fn);

      if (selector && typeof selector == "string")
        ret = jQuery.multiFilter(selector, ret);

      return this.pushStack(jQuery.unique(ret), name, selector);
    };
  }
);

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.

var a = $("a:first");
var log = console.log;

log(a["parent"]());
log(a["parents"]());
log(a["next"]());
log(a["prev"]());
log(a["nextAll"]());
log(a["prevAll"]());
log(a["siblings"]());
log(a["children"]());
log(a["contents"]());

If this blog was helpful, check out our full blog archive.

Stay up to date with our blogs.

Subscribe to receive email notifications for new blog posts.