Add data attribute to element and dynamically add value from class name

I want to add a data attribute to an element and dynamically give it the same value as the class name.

I used this script to do the same from the elements string, but instead I want to pass the value from the class name and don't know how to do it.

Script:

$('.newgroup').attr('data-price', function() {
var text = $(this).text();
return parseInt(text, 10); 
});

HTML

<div class="newgroup">/div>

It should look like this:

<div class="newgroup" data-price="newgroup">>/div>
+4
source share
2 answers

Just write the following:

$(".newgroup").attr("data-price", $('.newgroup').attr('class'));

.attr sets the attribute value and .attr ('class') returns the class name

See plunkr

As you can see in the screenshot, the attribute is added :

enter image description here

+2
source

, attribute, :

$('.newgroup').attr('data-price', function() {
    return $(this).attr('class');
});

.

+2

All Articles