Corentin Branquet Corentin Branquet - 6 months ago 27
jQuery Question

Set data attribute with Jquery

I've this line of code :

<p class="main-description" >Hello world</p>


I want to add a data attribute with JQuery, I can't change the HTML

So I try this :

$('.main-description').data('data-custom','5s');


The final result should be this but it does not work

<p class="main-description" data-custom="5s" >Hello world</p>

Answer

You need to use attr()

$('.main-description').attr('data-custom', '5s');
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p class="main-description">Hello world</p>

For the difference between them refer : jQuery Data vs Attr?

Comments