4

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>
4
  • 2
    same value as the class name? so why parsing the text of it. Commented May 12, 2016 at 6:43
  • 1
    demo only if only class exists demo1 if you have other class you can play inside function to target which class you want Commented May 12, 2016 at 6:44
  • 1
    $(".newgroup").attr("data-price", "newgroup") I think this will be enough for you. Commented May 12, 2016 at 6:45
  • 1
    just use... return this.className; .. jsfiddle.net/mohamedyousef1980/A6BXk/54 Commented May 12, 2016 at 6:54

2 Answers 2

2

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

Sign up to request clarification or add additional context in comments.

Comments

2

You can make use of the following to assign the attribute, the value as the class-name:

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

Refer to the demo.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.