stefanhalbeisen
stefanhalbeisen

Reputation: 123

Get data-attribute of an element by another data-attribute as identifier

I have dynamically created elements with no id, but a data-attribute id like: data-jobtypid="2".

This dynamically created element has other data-attributes, which I would like to read and I only know the data-jobtypid as identifier and the classname of all dynamically created elements.

So I tryed something like this:

var cache_color = $('.addjob_choose_paymentbtn')
                   .filter('[data-jobtypid="2"]')
                   .getAttribute("data-jobtypcolorhover");

Has someone an idea for me to solve this?

Regards

Upvotes: 2

Views: 692

Answers (2)

Kamil Kiełczewski
Kamil Kiełczewski

Reputation: 92467

try

let c= document.querySelector('.addjob_choose_paymentbtn[data-jobtypid="2"]')
         .dataset.jobtypcolorhover;

console.log(c);
<div class="addjob_choose_paymentbtn" data-jobtypid="2" data-jobtypcolorhover="blue">Hi</div>

Upvotes: 0

Jeto
Jeto

Reputation: 14927

Simply use an attribute selector combined with $.data():

var cache_color = $('.addjob_choose_paymentbtn[data-jobtypid="2"]')
  .data('jobtypcolorhover');

console.log(cache_color);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="addjob_choose_paymentbtn" data-jobtypid="2" data-jobtypcolorhover="red">div</div>

You can alternatively use .attr('data-jobtypcolorhover'), which is the correct way to access an attribute in jQuery as mentioned in the comments above. However, $.data() is a tiny beat cleaner.

Upvotes: 3

Related Questions