phantom phantom - 4 months ago 6
Javascript Question

Get value of data attribute using jQuery in parent element

I still don't think I have got my head around how jQuery's

parent()
method works.

I have the following html code whereby on click of
.spot-info
I want to get the value of
data-test
.

<div class="spot" id="spot-1" data-test="12345">
<div class="spot-main">
<span>Test</span>
<a href="#" class="spot-info">view</a>
</div>
</div>

<div class="spot" id="spot-2" data-test="67891">
<div class="spot-main">
<span>Test</span>
<a href="#" class="spot-info">view</a>
</div>
</div>


Please see my js attempt below:

$('.spot-info').click(function ( e ) {
e.preventDefault();
var test = $(this).parent().parent().data('data-test');
console.log(test);
});


This test is logging
undefined
in the console. I would have thought this would work as it is checking the parent of the parent of
.spot-info
.

Also, is there any better way of doing it rather than chaining lots of
parent(0
methods together? I would fear that if the html changes this would break, bur perhaps this is the disadvantage of using jquery.

Answer

try attr instead. Also, try 'closest' instead of referring to the parent twice:

$('.spot-info').click(function ( e ) {
    e.preventDefault();
    var test = $(this).closest('spot').attr('data-test');
    console.log(test);
});