简体   繁体   中英

Select all parents which has same classname

i need to select all parents which has same class using jQuery

now i can select only one element but i want to select all parent elements

<div class="text">
 <div class="text">
  <div class="text">
   <div class="text">
    <div class="text">
     <div class="text-3">
      hi
     </div>
    </div>
   </div>
  </div>
 </div>
</div>

in this i need to select the parent elements of .text-3 which has text as a classname

You can use parents() :

Get the ancestors of each element in the current set of matched elements, optionally filtered by a selector.

var parents = $('.text-3').parents('.text')

or has() :

Reduce the set of matched elements to those that have a descendant that matches the selector or DOM element.

var parents = $('.text').has('.text-3')

use .parents() :

Description: Get the ancestors of each element in the current set of matched elements, optionally filtered by a selector.

$('.text-3').parents('.text')

to iterate over each element, use:

$('.text-3').parents('.text').each(function(){
   //code here
});

Working Fiddle

Try using .parents() :

$('.text-3').parents('.text')

Example from the linked site:

Find all parent elements of each b.

<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>parents demo</title>
  <style>
  b, span, p, html body {
    padding: .5em;
    border: 1px solid;
  }
  b {
    color: blue;
  }
  strong {
    color: red;
  }
  </style>
  <script src="//code.jquery.com/jquery-1.10.2.js"></script>
</head>
<body>

<div>
  <p>
    <span>
      <b>My parents are: </b>
    </span>
  </p>
</div>

<script>
var parentEls = $( "b" ).parents()
  .map(function() {
    return this.tagName;
  })
  .get()
  .join( ", " );
$( "b" ).append( "<strong>" + parentEls + "</strong>" );
</script>

</body>
</html>

My parents are: SPAN, P, DIV, BODY, HTML

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