jQuery Slice Function Example

Let's have a closer look at the jQuery .slice() function.

Demo Code Download


The .slice() function allows us to easily specify a subset of elements to perform actions on. It takes two parameters: start and end indices of sub elements in a matched parent element. Lets have a look at an example of the slice jQuery function in action. Further Reading »


jQuery Function Demo - jQuery4u.com

Demo: Using .slice() to perform actions on a subset of elements.

Run Demo View Code

Slice 1 Slice 2 Slice 3


The download package includes all the inline HTML, CSS, JavaScript, jQuery and images required for the .slice() function demo so you can try it yourself and change as you please.

The full code listing for all jQuery functions have been now added to GitHub, you can get them there, we are making them work with the latest versions of jQuery!


<!-- Copyright 2011 jQuery4u.com -->
<!DOCTYPE html>
<title>jQuery Function Demo - jQuery4u.com</title>
    <script src="http://www.jquery4u.com/function-demos/js/jquery-1.6.4.min.js"></script>
    <script src="http://www.jquery4u.com/scripts/function-demos-script.js"></script>
    <script src="http://www.jquery4u.com/scripts/jquery.sparkline.min.js"></script>

    <script type="text/javascript">

    var JQFUNCS =
            /* ------------------------------ slice Demo ------------------------------ */
                run: function(id)
                    var trs = $('#'+id+' table tr'), selectedRow = 0;
                    $('#'+id+' button').live('click', function(e)
                        trs.css("background", "");
                        selectedRow = (selectedRow == 5) ? 1 : selectedRow += 1;
                        trs.slice(selectedRow, selectedRow+1).css("background", "orange");
                        var slices = trs.slice(selectedRow, selectedRow+1).text().trim().replace(/\s/g, "");
                        $('#sparklinesExample').sparkline('html', { type: 'pie', height: '9.0em' });

                reset: function(id)


    <style type="text/css" media="screen">
        .demoarea {



<h3>Demo: Using .slice() to perform actions on a subset of elements.</h3>
<p><a href="#" id="slice-demobtn" class="demobtn btn actionr">Run Demo</a> <a href="#" id="slice-codebtn" class="codebtn btn actionr">View Code</a> <a href="#" id="slice-resetbtn" class="resetbtn btn actionr" style="display: none;">Reset</a></p>
<div class="demoarea" id="slice" style="border:1px solid orange; padding:25px;height: 280px;width: 550px;">
    <div style="width:300px;float:left;">
<table border="1">
<th>Slice 1</th>
<th>Slice 2</th>
<th>Slice 3</th>
<button class="btn">Slice Me!</button>
    <div style="width:150px; display:inline-block; height: 160px;font-size:16px;color:blue;margin: 50px;">
        <span id="sparklinesExample"></span>

<!-- Copyright 2011 jQuery4u.com -->