Search code examples
jquerytargeting

how to apply actions to only one instance of a class


I have a form that needs to dynamically generate fields and those fields have various jquery functions called on them. Basically I am using slideUp and slideDown to show different options based on what the user selects. Consider the following code

    <div class="test">
    <div class="red" style="width:100px;height:100px;background-color:red; margin-bottom:10px;"></div>
    <div class="green" style="width:100px;height:100px;background-color:green;margin-bottom:10px;"></div>
</div>

<div class="test">
    <div class="red" style="width:100px;height:100px;background-color:red;margin-bottom:10px;"></div>
    <div class="green" style="width:100px;height:100px;background-color:green;margin-bottom:10px;"></div>
</div>

And the jquery

$('.green').hide();

        $('.red').click(function(){
            $('.green').show();
            });

Basically I want only the green box that is after the red one to show. While this example is simple and I could just duplicate my code and give the second item a different id, my real form is way more complex so what I would like to do is find a way to target items by classname within each "test" div.


Solution

  • Both answers are good, i'm just adding another option :

    $('.red').click(function () {
        $(this).siblings('.green').show();
    });
    

    Jquery doc : http://api.jquery.com/siblings/