Divern
Divern

Reputation: 363

How to get the data- value when clicking on children from parent with jQuery?

Ok, so I am trying to get the data- attribute from the parent div instead of getting it from every anchor. I have tried using closest, but that does not work. Here is my following code.

<div class="cat black">
  <a class="cat_col" data-color="black">Tom</a>
  <a class="cat_col" data-color="black">Cotton</a>
  <a class="cat_col" data-color="black">Major</a>
</div>

and this is the jQuery code I have:

$('body').on('click', '.cat_col', function(event) {
  event.preventDefault();
  var $CatColor = $(this).data("color");                 
  getCats ($showCategory);
});

I don't have a problem with this, but once I start populating things, it will get a little confusing, plus there will be more options. So, I was wondering if it was possible to get the data- from the parent div instead of every child. So, do something like this.

<div class="cat black" data-color="black">
  <a class="cat_col">Tom</a>
  <a class="cat_col">Cotton</a>
  <a class="cat_col">Major</a>
</div>

$('body').on('click', '.cat_col', function(event) {
  event.preventDefault();
  var $CatColor = $(this).closest.data("color");                 
  getCats ($showCategory);
});

What am I doing wrong? or is this just impossible?

Upvotes: 0

Views: 635

Answers (4)

dh6984
dh6984

Reputation: 108

If I understand you correctly, you want to get the color from the parent div, if so use the parent() function like so:

$('body').on('click', '.cat_col', function(event) {
    event.preventDefault();
    var $CatColor = $(this).parent().data("color");                 
    console.log($CatColor);
});

Here is a fiddle.

Upvotes: 1

Curiousdev
Curiousdev

Reputation: 5788

You can also find closest("div") as well

$('body').on('click', '.cat_col', function(event) {
  event.preventDefault();
  var $CatColor = $(this).closest("div").data("color");                 
  alert($CatColor);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="cat black" data-color="black">
  <a class="cat_col">Tom</a>
  <a class="cat_col">Cotton</a>
  <a class="cat_col">Major</a>
</div>

Upvotes: 2

Mohtisham Zubair
Mohtisham Zubair

Reputation: 723

$('body').on('click', '.cat_col', function(event) {
  event.preventDefault();
  var $CatColor = $(this).parent().data("color");
  alert($CatColor);
  getCats ($showCategory);
});

Upvotes: 1

Oleksandr  Maliuta
Oleksandr Maliuta

Reputation: 516

You need to specify which element is closest

$('body').on('click', '.cat_col', function(event) {
  event.preventDefault();
  var $CatColor = $(this).closest('.cat').attr('data-color');                 
  getCats ($showCategory);
});

Upvotes: 1

Related Questions