Reputation: 3911
Please note that this question already has an answer here but the answer is provided in jQuery, I need similar thing to be done with vanilla javascript.
Here's my issue in detail. I have a price string to display in a page which will be in html as <span>60.00</span>
I want to transform the string into something like this <span>60,<sup>00</sup></span>
.
Here's the code I have tried.
let value = "60.00";
value = value.replace(".", ",");
let values = value.split(',');
var tag = document.createElement("sup");
var text = document.createTextNode(values[1]);
text = tag.appendChild(text);
let text1 = JSON.stringify(text);
alert(values[0]+text1);
If I run this code I get 60{}
as an output. 60,⁰⁰
this is the desired output.
Upvotes: 0
Views: 2366
Reputation: 6788
You're almost there with your current code but you're concatenating objects and strings. That doesn't work. You have to fill the elements one by one or convert the HTML elements to strings with .outerHTML
:
let value = "60.00";
value = value.replace(".", ",");
let values = value.split(',');
var tag = document.createElement("sup");
var text = document.createTextNode(values[1]);
tag.appendChild(text);
document.getElementById('output').innerHTML = values[0];
document.getElementById('output').appendChild(tag);
alert(values[0] + tag.outerHTML);
<div id="output"></div>
Upvotes: 2
Reputation: 89
let span = document.querySelector("span");
let value = span.innerHTML;
const sup = `<sup>${value.split('.')[1]}</sup>`;
value = `${value.split('.')[0]}.${sup}`;
span.innerHTML = value;
<span>10.00</span>
Upvotes: 0
Reputation: 1504
Instead of adding a sup
tag, why not add the string <sup></sup>
instead?
let span = document.querySelector("span");
let value = span.innerHTML;
const sup = `<sup>${value.split('.')[1]}</sup>`;
value = `${value.split('.')[0]},${sup}`;
span.innerHTML = value;
<span>60.00</span>
Upvotes: 1