开发者

Is parentsUntil() the best function to use? Jquery

开发者 https://www.devze.com 2023-04-12 08:34 出处:网络
Given the html: <div class=\"a\"> <div class=\"b\"> <div class=\"c\"> <div class=\"d\">

Given the html:

     <div class="a">
        <div class="b">
           <div class="c">
             <div class="d">
             </div>
           </div>
          <div class="d">
          </div>
        </div>
     </div>

Im interested in the selecting the parent element with class a applied to it when any element with the class 'd' is clicked.

I have the following javascript / jQuery, but it seems very messy. Is there a neater way?

<script>
   $('.d').click(function(){
      var elementA =  $(this).parentsUntil('.a'开发者_运维技巧).last().parent();    
   })
</script>


You want $(this).closest('.a').


you can also do:

$(".d").click(function() {
    // parents() will walk up through parent nodes. If you
    // pass a selector, the set will be filtered. If not,
    // you get the full list of parent elements.
    var elementA = $(this).parents(".a");
});

docs here.

hope that helps! cheers.

0

精彩评论

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

关注公众号