In jQuery there are a few colon selectors like
:prev, :next, :last
My question is:
prev()
, next()
, last()
. What is the purpose of having 2 different ways?Any basic examples would be really great.
jQuery provides some very powerful selection expressions using colon (:) syntax. Things like :first , :odd , and :even let you write code like: $('#content a:first') to get the first anchor within #content, or $('tr:odd') to get the odd numbered rows of a table.
jQuery selectors allow you to select and manipulate HTML element(s). jQuery selectors are used to "find" (or select) HTML elements based on their name, id, classes, types, attributes, values of attributes and much more. It's based on the existing CSS Selectors, and in addition, it has some own custom selectors.
You can specify any number of selectors to combine into a single result. This multiple expression combinator is an efficient way to select disparate elements. The order of the DOM elements in the returned jQuery object may not be identical, as they will be in document order.
The :even selector selects each element with an even index number (like: 0, 2, 4, etc.). The index numbers start at 0. This is mostly used together with another selector to select every even indexed element in a group (like in the example above).
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").
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();
});
}
}
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With