Jerry Svensson Jerry Svensson - 6 months ago 18
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.

Script:

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


HTML

<div class="newgroup">/div>


Should looks like this:

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

Answer

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

Comments