简体   繁体   中英

Selecting a child element of an adjacent element

I'm attempting to use .parents to select an element in an adjacent ul so that I can click one to affect the other.

I can select the parent .outside of both ul, starting from the span within .ulB however when I ask it to go back in and select .ulA it doesn't like it.

Any ideas? It is possible to do this using this method or at all? Thanks.

Example code below.

<!DOCTYPE html>
<html>
<head>

<style>
  .ancestors * { 
  display: block;
  border: 2px solid lightgrey;
  color: lightgrey;
  padding: 5px;
  margin: 15px;}
</style>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script>
$(document).ready(function(){
    $("span").parents(".outside > .ulA").css({"color": "red", "border": "2px solid red"});
});
</script>

</head>

<body class="ancestors">
  <div class="outside" style="width:500px;">

    <ul class="ulA">  
      <li></li>
    </ul>

    <ul class="ulB">
      <li>
        <span>span</span>
      </li>
    </ul>

  </div>
</body>

</html>

There's no parent of a span matching .outside > .ulA . You need to find the parent first, then find the .ulA descendant:

$("span").
  parents(".outside").
  find(".ulA").
  css({"color": "red", "border": "2px solid red"});

  $("span").parents(".outside").find(".ulA").css({ "color": "red", "border": "2px solid red" }); 
  .ancestors * { display: block; border: 2px solid lightgrey; color: lightgrey; padding: 5px; margin: 15px; } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <div class="ancestors"> <div class="outside" style="width:500px;"> <ul class="ulA"> <li></li> </ul> <ul class="ulB"> <li> <span>span</span> </li> </ul> </div> </div> 

The parents selector does not exist.

You first need to find the parent and then search within it.

Also - use closest . You don't need parents (unless filtering later) , and also it's faster than parent . closest already returns the first match.

$("span").closest(".outside").find(".ulA").css({"color": "red", "border": "2px solid red"});

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