4

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);
})
1
  • 1
    closest() - $(this).closest('.message').data("id"); Commented Sep 26, 2014 at 13:11

4 Answers 4

10

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>

Sign up to request clarification or add additional context in comments.

1 Comment

thanks it works, but i have another issue, what if my spans are not children of parent with class message, what should i use instead of method closest. For more information i'll provide this fiddle: jsfiddle.net/g2Rxc/93
2

You need to use parents() instead of parent()

$('.sms').click(function(){
    var id = $(this).parents('.message').data("id");
    alert(id);
});

Comments

2

Use closest() to find the ancestor in hierarchy with specified selector

$('.sms').click(function(){
    var id = $(this).closest('.message').data("id");
    alert(id);
});

Comments

0

.parents(selector) ParentS will search up in the DOM

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.