lalexa
lalexa

Reputation: 453

get parent element by class using jquery

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

Answers (4)

Arun P Johny
Arun P Johny

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

Naramsim
Naramsim

Reputation: 8782

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

Upvotes: 0

Bhushan Kawadkar
Bhushan Kawadkar

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

Mithun Satheesh
Mithun Satheesh

Reputation: 27845

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

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

Upvotes: 2

Related Questions