Cover by Cody Lindley

Safari, the world’s most comprehensive technology and business learning platform.

Find the exact information you need to solve a problem on the fly, or go deeper to master the technologies and skills you need to succeed

Start Free Trial

No credit card required

O'Reilly logo

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 ...

Find the exact information you need to solve a problem on the fly, or go deeper to master the technologies and skills you need to succeed

Start Free Trial

No credit card required