简体   繁体   中英

How can I access a div from another div?

<div id="a">
  <div id="b">
      <div id="c"></div>
  </div>

  <div id="a2"></div>
</div>

I want from div where id="c" to access div where id="a2" , but it's not working:

$("#c").parentsUntil("#a").find("#a2");

According to the documentation for parentsUntil :

Get the ancestors of each element in the current set of matched elements, up to but not including the element matched by the selector, DOM node, or jQuery object.

What this means is that parentsUntil is returning all of the parents of #c except for #a . (Which in this case is just #b .) And none of those elements contain #a2 . Use closest instead:

 $("#c").closest("#a").find("#a2").css('color', 'red');
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div id="a"> <div id="b"> <div id="c"> </div> </div> <div id="a2"> test </div> </div>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM