Reputation: 1582
I'm trying to remove all but the first 4 characters from a data attribute of each div, the markup below as follows:
HTML
<div class="grid-block" data-category="17.40—18.20">text</div>
<div class="grid-block" data-category="18.40—19.40">text</div>
<div class="grid-block" data-category="19.20—20.20">text</div>
<div class="grid-block" data-category="20.40—21.30">text</div>
and the desired result would be this:
<div class="grid-block" data-category="1740">text</div>
<div class="grid-block" data-category="1840">text</div>
<div class="grid-block" data-category="1920">text</div>
<div class="grid-block" data-category="2040">text</div>
ideally removing the dot from each too, but that's not essential. Not sure if this is possible, any suggestions would be greatly appreciated!
Upvotes: 0
Views: 697
Reputation: 303
try replace
and subString
to get your result
something like:
var x = document.getElementByClassName("grid-block")[0];
var inner = x.innerHTML;
inner = inner.replace('-','').replace('.','').subString(0,4); // subString(start,length)
x.innerHTML = inner;
Upvotes: 0
Reputation: 240888
Iterate over all the elements with [data-category]
attributes, and remove the .
character from the attribute and then use .substring(0, 4)
to retrieve the first 4 characters:
$('[data-category]').each(function () {
var category = $(this).data('category').replace('.', '').substring(0, 4);
$(this).attr('data-category', category);
});
You don't need jQuery to do this, though:
var elements = document.querySelectorAll('[data-category]');
Array.prototype.forEach.call(elements, function (el) {
var category = el.dataset.category.replace('.', '').substring(0, 4);
el.setAttribute('data-category', category);
});
Upvotes: 2