user2669997
user2669997

Reputation:

get parent id of a class from a click of the child class

I have four <div> container as shown below:

 <div class="parentBox">
  <div class="childBox" id="20">
      <div>some content with in this div</div>
      <div>another div with more sontent</div>
  </div>
</div>

I want to get the childBox id into a jQuery variable when I click anywhere within the childBox div. I've tried the following which gives me undefined

 $('.parentBox').click(function (event) {
    var id = $(this).attr('id');
    console.log(id);
});

also tried this which gave me parent is not a function

var id = $(this).parent().attr('id');

and tried this which just gives me a blank in console log

var id = event.target.id;

Can someone please help?

     $('.parentBox').click(function (event) {
        var id = $(this).attr('id');
        console.log(id);
        
        //does not work
        console.log($(this).parnet().attr('id'));
        
        //also does not work
        console.log(event.target.id);
    });
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="parentBox">
      <div class="childBox" id="20">
          <div>some content with in this div</div>
          <div>another div with more sontent</div>
      </div>
    </div>

Upvotes: 3

Views: 453

Answers (3)

Goran Stoyanov
Goran Stoyanov

Reputation: 2311

If you want the .childBox id when clicking on .childBox div you can just hook the click event on the .childBox class:

$('.childBox').click(function (event) {
    var id = $(this).attr('id');
    console.log(id);
});

EDIT:

If you want to access the .childBox from .parentBox event you can do this:

$('.parentBox').click(function (event) {
    var id = $(this).find('.childBox').attr('id');
    console.log(id);
});

When dynamically adding children it's a good idea to hook the event on the parent or on the document object like this:

$(document).on('click', '.childBox' , function() {
  console.log($(this).attr('id'));
});

Upvotes: 2

Aziz Sirojiddinov
Aziz Sirojiddinov

Reputation: 89

try this it should work

$(".parentBox").on('click', "div.childBox",
     function() {var myId = $(this).attr('id'); });

Upvotes: 0

Patrissol Kenfack
Patrissol Kenfack

Reputation: 863

You can do it as follows:

$('.parentBox').click(function (event) {
    var id = $($(this).children('div')[0]).attr('id');
    console.log(id);
});

Upvotes: 0

Related Questions