Reputation: 17915
Here is my HTML fragment. I'm subscribing to "click" event of anchor "inquire". How do I traverse up to get data-driverid
value?
<div class="DriverWrapper" data-driverid="108WW" style="background-color: Silver; padding: 4px 4px 4px 4px; page-break-before: always;">
<strong>Driver ID:</strong> 108WW
</div>
<table style="width: 100%;">
<tr>
<td style="vertical-align: top; width: 20%">
<strong>174794</strong>
<a href="#" class="inquireTripLink">inquire</a>
EDIT:
I tried this and it shows alert with null
$(".inquireTripLink").on("click", function (event)
{
event.preventDefault();
var driverId = $(this).closest('.DriverWrapper').data('driverid');
alert(driverId);
Upvotes: 1
Views: 40
Reputation: 144739
You can use closest
method.
$('.inquireTripLink').click(function(){
var id = $(this).closest('.DriverWrapper').data('driverid');
});
Update: The div
element is not parent of the clicked element, you have closed the div
tag after strong
tag. You can use prev
method:
$('.inquireTripLink').click(function(){
var id = $(this).closest('table').prev('div').data('driverid');
});
Upvotes: 2
Reputation: 208032
Try this:
$(".inquireTripLink").on("click", function (event) {
event.preventDefault();
var driverId = $(this).closest('table').prev('.DriverWrapper').data('driverid');
alert(driverId);
})
Your link appears to be in a table which isn't a child of the div, but a sibling.
Upvotes: 1
Reputation: 78750
$(this).closest("table").prev(".DriverWrapper").data("driverid");
It will break if you change your markup, but it works with your posted html. You might consider adding a common parent and then doing the following instead:
$(this).closest("COMMON PARENT").find(".DriverWrapper").data("driverid");
Upvotes: 0
Reputation: 324810
Try $(this).closest("[data-driverid]").data("driverid")
Upvotes: 0