Mostapha Ghribi
Mostapha Ghribi

Reputation: 25

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");

Upvotes: 0

Views: 626

Answers (1)

David
David

Reputation: 218798

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>

Upvotes: 1

Related Questions