user6002037
user6002037

Reputation:

Get value of data attribute using jQuery in parent element

I have the following HTML code where onclick 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 thought this would work checking the parent of the parent of .spot-info.

Also, is there way chaining a lot of parent(0) methods together rather than using jQuery.

Upvotes: 7

Views: 14557

Answers (3)

Mart Oosterveld
Mart Oosterveld

Reputation: 162

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

Upvotes: 13

Zakaria Acharki
Zakaria Acharki

Reputation: 67505

Better if you could use closest() or parents() ,so instead of :

$(this).parent().parent().data('test');

Use :

$(this).closest('.spot').data('test');
$(this).parents('.spot').data('test');

NOTE : The main problem come from .data('data-test'); When you use data() function you shouldn't add the string data- at the start.

Hopet his helps.


Working snippet

$('.spot-info').click(function ( e ) {
    e.preventDefault();
    var test = $(this).closest('.spot').data('test');
  
    console.log(test);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<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>

Upvotes: 3

itamar
itamar

Reputation: 3967

Not sure - but I think it's this:

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

You don't need the data- prefix when fetching the data with .data()

Upvotes: 0

Related Questions