katit
katit

Reputation: 17915

jQuery selector help needed

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>&nbsp;108WW
</div>

<table style="width: 100%;">
    <tr>
        <td style="vertical-align: top; width: 20%">
            <strong>174794</strong>&nbsp;
            <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

Answers (4)

Ram
Ram

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');
});

http://jsfiddle.net/J8cWT/

Upvotes: 2

j08691
j08691

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.

jsFiddle example

Upvotes: 1

James Montagne
James Montagne

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

Niet the Dark Absol
Niet the Dark Absol

Reputation: 324810

Try $(this).closest("[data-driverid]").data("driverid")

Upvotes: 0

Related Questions