Reputation: 217
I wanted to figure out if it is possible to add a new data attribute to an existing html element. So for instance:
<button class="confirm-button" data-id=560>Click Me</button>
I will like to be able to add a new data attribute using jquery like
<button class="confirm-button" data-text="justaddedattr" data-id=560>Click Me</button>
Upvotes: 1
Views: 906
Reputation: 68933
You can try with jQuery's .attr()
$('.confirm-button').attr('data-text', 'justaddedattr');
console.log($('.confirm-button').data('text'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button class="confirm-button" data-id=560>Click Me</button>
You can also try .data()
$('.confirm-button').data('text', 'justaddedattr');
console.log($('.confirm-button').data('text'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button class="confirm-button" data-id=560>Click Me</button>
Upvotes: 4