Home > OS >  How to add HTML tag for a specific part of the string (javascript)
How to add HTML tag for a specific part of the string (javascript)

Time:09-16

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. If I remove the JSON.stringify() I get 60[object Text] 60,⁰⁰ this is the desired output.

PS: I want this to be done with pipes in angular that's why I wanted this way. If there's any related pipes please let me know.

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>

CodePudding user response:

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>

  • Related