Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add Data attribute to element and dynamically add value from string

Is is possible to assign a data value to the element below - and use the numbers in the string as the value with jQuery/Vanilla JS?

I want this:

<div class="priceinfo col5">2560kr</div>

To look like this:

<div class="priceinfo col5" data-price="2560">2560kr</div>

The value is dynamic - the class of the element is the same.

like image 376
Jerry Svensson Avatar asked Apr 13 '26 00:04

Jerry Svensson


1 Answers

This can be done with the jQuery attr() method:

var someValue = 2560;
$('.priceinfo.col5').attr('data-price', someValue);

You can set any attribute, including custom attributes such as HTML5 data- attributes, using attr().


You can also pass a function instead of a fixed value to .attr():

$('.priceinfo.col5').attr('data-price', function() {
    var text = $(this).text();
    return parseInt(text, 10); //drops the non-numeric characters at the end of the text
});

This is extremely useful when there are multiple elements in the jQuery set -- multiple elements with the classes priceinfo and col5.


If the value might sometimes have initial non-numeric characters, then you could use a regular expression to parse the text:

$('.priceinfo.col5').attr('data-price', function() {
    var text = $(this).text();
    var matches = /\d+/.exec(text);
    if (!matches) {return '';}
    return parseInt(matches[0], 10);
});
like image 140
DLeh Avatar answered Apr 14 '26 13:04

DLeh



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!