O'Reilly logo

jQuery Cookbook by Cody Lindley

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

3.6. Performing an Action on a Subset of the Selected Set

Problem

You need to perform an action on a set of tags, but there is no way to isolate these tags from all the other tags on the page in a jQuery selection set.

Solution

We can use the slice() method to filter the selection set to a subset. We pass it a starting index value and an ending index value, then we can chain our action at the end:

<!DOCTYPE html
     PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
     "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <meta http-equiv="Content-Type" content="text/html;charset=UTF-8" />
    <title>Chapter 3 - Recipe 6 - Performing an action on a subset of the selected 
set</title>
    <script type="text/javascript" 
src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
    <script type="text/javascript">
    <!--
        (function($){
            $(document).ready(function(){

  $("p").slice(1,3).wrap("<i></i>"); }); })(jQuery); //--> </script> </head> <body> <p> Lorem ipsum dolor sit amet, consectetur adipiscing elit. Proin eget nibh ut tortor egestas pharetra. Nullam a hendrerit urna. Aenean augue arcu, vestibulum eget faucibus nec, auctor vel velit. Fusce eget velit non nunc auctor rutrum id et ante. Donec nec malesuada arcu. Suspendisse eu nibh nulla, congue aliquet metus. Integer porta dignissim magna, eu facilisis magna luctus ac. Aliquam convallis condimentum purus, at lacinia nisi semper volutpat. Nulla non risus justo. In ac elit vitae elit ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required