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);
})
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>
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