Select the nearest DOM element with jQuery

99封情书 提交于 2020-01-03 03:28:46

问题


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.


回答1:


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



回答2:


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

http://jsfiddle.net/UUdXk/



来源:https://stackoverflow.com/questions/6476762/select-the-nearest-dom-element-with-jquery

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!