Change specific numbers in a string
I have a string that sometimes contains css font sizes. For example:
str = '<span style="font-size: 200px;white-space:nowrap;">Text</span>
<br><span style="color:#555555;font-size:10px;">Some otherText</span>';
I need to change all font sizes by multiplying them by a set factor, for example 1.5
var ratio = 1.5;
Finding and replacing is not my strong suit. How do I search for a string for all font sizes and then do math on each number?
So this line with this relationship would become:
str = '<span style="font-size: 300px;white-space:nowrap;">Text</span>
<br><span style="color:#555555;font-size:15px;">Some otherText</span>';
source to share
Suppose it is like a string and there is no better way (if it came from innerHTML
or so you are doing it wrong) then ...
var fauxDocFrag = document.createElement("div");
var elements, i, len;
fauxDocFrag.innerHTML = str;
elements = fauxDocFrag.getElementsByTagName("*");
for (i = 0, len = elements.length; i < len; i++) {
elements[i].style.fontSize = (parseInt(elements[i].style.fontSize) * 1.5)
+ "px";
}
str = fauxDocFrag.innerHTML;
jsFiddle .
If your browser doesn't suck ...
var fauxDocFrag = document.createElement("div");
fauxDocFrag.innerHTML = str;
[].forEach.call(fauxDocFrag.getElementsByTagName("*"), function(element) {
element.style.fontSize = (parseInt(elements.style.fontSize) * 1.5)
+ "px";
});
str = fauxDocFrag.innerHTML;
If any of the ads were missing in the attribute style
, you can use getComputedStyle()
.
I didn't use the real documentFragment
one because it doesn't support the property innerHTML
.
source to share