Reputation: 277
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.
Upvotes: 3
Views: 12040
Reputation: 76426
You can do that with plain javascript as well:
function setAttribute(selector, attribute, value) {
var elements = document.querySelectorAll(selector);
for (var index = 0; index < elements.length; index++) {
elements[index].setAttribute(attribute, (typeof value === "function" ? value(elements[index]) : value));
}
}
Upvotes: 8
Reputation: 24395
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);
});
Upvotes: 8