copenndthagen
copenndthagen

Reputation: 50740

jQuery colon selectors

In jQuery there are a few colon selectors like

:prev, :next, :last

My question is:

  1. Are they truly part of jQuery, because they are actually used on DOM elements?
  2. We seem to have equivalent methods as well in jQuery prev(), next(), last(). What is the purpose of having 2 different ways?

Any basic examples would be really great.

Upvotes: 5

Views: 8438

Answers (4)

Xeo
Xeo

Reputation: 357

Here is how I made a slider with all sorts of selectors and traversing of objects.

$('#next').click(function () {
  if (!$('*').is(':animated')) {
    if ($('div.display:visible').is(':nth-child(3)')) {

      $('div.display:visible').fadeOut();
      $('div.display:first').fadeIn(function () {
        $(this).children().fadeIn();
      });

    } else {

      $('div.display:visible').fadeOut().next().fadeIn(function () {
        $(this).children().fadeIn();
      });
    }
  }

});

$('#prev').click(function () {
  if (!$('*').is(':animated')) {
    if ($('div.display:visible').is(':nth-child(1)')) {
      $('div.display:visible').fadeOut();
      $('div.display:last').fadeIn(function () {
        $(this).children().fadeIn();
      });

    } else {
      $('div.display:visible').fadeOut().prev().fadeIn(function () {
        $(this).children().fadeIn();
      });
    }
  }

});

Upvotes: 2

BoltClock
BoltClock

Reputation: 724092

jQuery does not have :prev or :next selectors, I have no idea where you came across them. There is a :last selector, though, as well as :first, provided by the Sizzle selector library, used by jQuery. It is a non-standard selector, not part of CSS, and is thus implemented in JavaScript.

One purpose of the :last selector over the .last() method is so you can use it to filter elements in the middle of a selector sequence, like this (note that :last and :last-child are not the same):

$('.a > .b:last > .c')

Rather than having to write a chain of methods like this:

$('.a').children('.b').last().children('.c');

By the way, the "colon selectors" you refer to are called pseudo-classes (colloquially but incorrectly known as "pseudo-selectors").

Upvotes: 10

Liam Bailey
Liam Bailey

Reputation: 5905

The colon represents a filter like to get the selected option in a dropdown I would use $("select option:selected") or to get a checked radio box I would use $("input[type=radio]:checked");

There are no :prev and :next filters, but you can find a full list of filters here http://api.jquery.com/category/selectors/

Upvotes: 1

Joseph Marikle
Joseph Marikle

Reputation: 78540

  1. yes, they are in the documentation
  2. sometimes you can't always include everything in the selector or want a subdivision of the selector.

e.g.

$(".mylist").each(function(){
  $(this).css("color","red");
  $(this).next().show();
})

Upvotes: 1

Related Questions