开发者

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>
$("开发者_如何学Go.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.


.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');


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

http://jsfiddle.net/UUdXk/

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜