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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With