Zelid
Zelid

Reputation: 7195

Select the nearest DOM element with jQuery

How to access the div with specific class that is on the same level of DOM using jQuery? I've tried .closest() but it doesn't find the element.

For example:

<!-- foreach loop starts { -->
<fieldset>
    <legend>Values</legend>
    <div class="characteristic-values">          
        <!-- many divs inside -->
    </div>
    <input type="button" class="add-charactersitic-value" value="Add Value" />
</fieldset>
<!-- } foreach loop ends -->

And JavaScript that tries to access the "charactersitic-values" but without success:

<script>
$(".add-charactersitic-value").live("click", function () {
    var addButton = $(this);

    // How to access the specified div from "addButton" variable?       
    // This doesn't work:
    //addButton.closest(".characteristic-values").append("<b>somedata</b>");    
});
</script>

How to access the "characteristic-values" in this case?

Thank you.

Upvotes: 1

Views: 5183

Answers (2)

Kevin Bowersox
Kevin Bowersox

Reputation: 94479

$(".add-charactersitic-value").prev(".characteristic-values");

http://jsfiddle.net/UUdXk/

Upvotes: 0

user578895
user578895

Reputation:

.prev('.characteristic-values');

.prev selects previous siblings. .closest selects parents (and the current item itself)

If the item is not the immediate previous sibling, this won't work (as .prev only selects that one element). You can do either of these instead:

.prevAll('.characteristic-values');
.parent().find('.characteristic-values');

Upvotes: 12

Related Questions