Corentin Branquet Corentin Branquet - 4 months ago 13x
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 :


The final result should be this but it does not work

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


You need to use attr()

$('.main-description').attr('data-custom', '5s');
<script src=""></script>
<p class="main-description">Hello world</p>

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