Corentin Branquet Corentin Branquet - 1 year ago 177
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>

Answer Source

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?

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download