0

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>
Pranav C Balan
  • 113,687
  • 23
  • 165
  • 188
Corentin Branquet
  • 1,556
  • 3
  • 17
  • 29

1 Answers1

2

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?

Community
  • 1
  • 1
Pranav C Balan
  • 113,687
  • 23
  • 165
  • 188