Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 621
Krishna Avatar asked Mar 04 '14 07:03

Krishna


3 Answers

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')
like image 152
Felix Avatar answered Oct 06 '22 23:10

Felix


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

like image 22
Milind Anantwar Avatar answered Oct 07 '22 00:10

Milind Anantwar


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

like image 30
Rahul Tripathi Avatar answered Oct 07 '22 00:10

Rahul Tripathi