jQuery, enumate/loop through chunks of data and repeat code

This example displays the power of JavaScript's referencing system. Clearly, there's a lot of repetitive code, repetitive class names, but using the ".each()" method of jQuery, we're able to assign events and functionality for each repeating section of the HTML.

by lasha

HTML

<div class="content-chunk">
    <h3>Chunk 1</h3>
    <ul>
        <li>item 01</li>
        <li>item 02</li>
        <li>item 03</li>
    </ul>
    <span class="clicked">clicked</span>
</div>
<div class="content-chunk">
    <h3>Chunk 2</h3>
    <ul>
        <li>item 01</li>
        <li>item 02</li>
        <li>item 03</li>
    </ul>
    <span class="clicked">clicked</span>
</div>
<div class="content-chunk">
    <h3>Chunk 3</h3>
    <ul>
        <li>item 01</li>
        <li>item 02</li>
        <li>item 03</li>
    </ul>
    <span class="clicked">clicked</span>
</div>

CSS

.content-chunk {
    background-color: #eee;
    padding: 5px 10px;
    margin-bottom: 10px;
}

h3 {
    margin: 0;
    padding: 0;
}

JavaScript

$(".content-chunk").each(function(){
    var $this = $(this);
    
    $this.find('li').click(function(e){
        $clicked = $(this);
        $this.find('.clicked').text("clicked " + $clicked.index());
    });
});