Kanaka k
Kanaka k

Reputation: 95

How to get id from inside div using jquery

How to get the id from the inside div. I have many div with class control but I want to get parent div id. How to get?

http://jsfiddle.net/cngt2ef6/7/

$(".getid").click(function() {
   alert($(this).closest('div').hasClass("control).attr("id"))
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="control" id="spa">
  Content
</div>
<div class="control" id="test">
  <div class="method">
    <a href="#" class="getid">Getid</a>
  </div>
</div>
<div class="control" id="awesome">
  Content
</div>

Upvotes: 3

Views: 1092

Answers (2)

dippas
dippas

Reputation: 60543

Besides closest() - which return the first single node parent - already mentioned you can use parents() , but in this case will return multiple nodes with the element/class/id targeted.

It is just an alternative to closest() in this case scenario

$(".getid").click(function() {
  console.log($(this).parents('.control').attr("id"))
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="control" id="spa">
  Content
</div>
<div class="control" id="test">
  <div class="method">
    <a href="#" class="getid">Getid</a>
  </div>
</div>
<div class="control" id="awesome">
  Content
</div>

Upvotes: 1

Zakaria Acharki
Zakaria Acharki

Reputation: 67505

The problem comes from :

  1. The closest selector that will return the first parent div (what is not what we need here).
  2. The hasClass() since it will return a boolean if the element has the given class or not. (in your case the first parent doesn't have the given class control)

Instead of using hasClass() you need to use the class selector directely in the closest() method like:

$(this).closest('div.control').attr("id");

$(".getid").click(function() {
  console.log($(this).closest('div.control').attr("id"));
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="control" id="spa">
  Content
</div>
<div class="control" id="test">
  <div class="method">
    <a href="#" class="getid">Getid</a>
  </div>
</div>
<div class="control" id="awesome">
  Content
</div>
Js:

Upvotes: 5

Related Questions