Jerry Svensson Jerry Svensson - 1 year ago 90
Javascript Question

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 have used this script to do the same from an elements┬┤string - but I want to pass the value from the class name instead, and not sure how to do that.


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


<div class="newgroup">/div>

Should looks like this:

<div class="newgroup" data-price="newgroup">>/div>

Answer Source

Simply write the following:

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

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

See the plunkr

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

enter image description here

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