Quantcast
Channel: Active questions tagged html - Stack Overflow
Viewing all articles
Browse latest Browse all 67527

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

$
0
0

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>

Viewing all articles
Browse latest Browse all 67527

Trending Articles