Reputation: 453
I have following html structure for example.
<div class="message" data-id="4">
<div>
<div class="msg-button">
<span class="sms"></span>
</div>
<div>
<div>
<div>
<span class="sms"></span>
</div>
</div>
</div>
</div>
</div>
When i click on elements with class sms
i need to get data-id attribute of element with class message
.
What i've done using jquery. It doesn't work for me. How can i get parent element by class? Thanks in advance!
$('.sms').click(function(){
var id = $(this).parent('.msg-button').siblings('.message').data("id");
alert(id);
})
Upvotes: 4
Views: 15548
Reputation: 388436
You need to use .closest(). .parent() will search only the direct parent node, since you are looking for a matching ancestor element use .closest()
$('.sms').click(function() {
var id = $(this).closest('.message').data("id");
alert(id);
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="message" data-id="4">
<div>
<div class="msg-button">
<span class="sms"></span>
</div>
<div>
<div>
<div>
<span class="sms">sms</span>
</div>
</div>
</div>
</div>
</div>
Upvotes: 10
Reputation: 28513
Use closest() to find the ancestor in hierarchy with specified selector
$('.sms').click(function(){
var id = $(this).closest('.message').data("id");
alert(id);
});
Upvotes: 2
Reputation: 27845
You need to use parents()
instead of parent()
$('.sms').click(function(){
var id = $(this).parents('.message').data("id");
alert(id);
});
Upvotes: 2