Reputation: 2710
I was trying to implementing an onClick handler for a div element. The parent div has data parameters present while the child divs do not have anything. When i clicked the children divs the onlick handler was being called but no data-parameters were present. And if i click the parent element then i could find the data-parameters. My question is if onclick action can be passed to the child elements how to do the same for data elements?
When i click the parent elements the log i get:
{
"id": "1",
"id1": "2",
"id3": "3"
}
When i click the child elements the log i get:
{}
Below is my code
$('.base_div').click(function(ev){console.log(ev.target.dataset);})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.2.3/jquery.min.js"></script>
<div class="col-md-4">
<div class="content-box base_div" data-id="1" data-id1="2" data-id3="3" style="padding: 30px;">
<div>
Child Element 1
</div>
<div class="test_class">
Child Element 2
</div>
</div>
</div>
Upvotes: 1
Views: 814
Reputation: 4305
You should replace ev.target
with ev.currentTarget
since event.currentTarget
always refers to the element to which the event handler has been attached.
event.target
identifies the element on which the event occurred.
Or you can simply replace ev.target
with this
.
$('.base_div').click(function(ev){console.log(ev.currentTarget.dataset);})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.2.3/jquery.min.js"></script>
<div class="col-md-4">
<div class="content-box base_div" data-id="1" data-id1="2" data-id3="3" style="padding: 30px;">
<div>
Child Element 1
</div>
<div class="test_class">
Child Element 2
</div>
</div>
</div>
Upvotes: 3