Miguel bastidas
Miguel bastidas

Reputation: 77

Select an specific text fragment in a HTML and add bold font with javascript

I want to add a bold font in an specific text fragment in a HTML. Where it says (10,90% TAE)* in the image.

enter image description here

The problem is that I have to inject it with Adobe target using javascript and this whole text numbers changes dynamically with javascript.

The original code is:

<p class="small clr-gray summary-interest" ing-unmask=""><span class="clr-black">10,39 % TIN</span> (10,90 % TAE)*</p>

And I want to bold (10,90% TAE)* like this with javascript:

<p class="small clr-gray summary-interest" ing-unmask=""><span class="clr-black">10,39 % TIN</span> <b>(10,90 % TAE)*<b></p>

I tried using the split method and select the part I want to bold but I dont know how to add it right:

"TIN":

var startN = document.querySelector("#summary-region > div > div > div:nth-child(2) > div:nth-child(2) > p.small.clr-gray.summary-interest").innerHTML.split(" ")[3];

"TAE)*":

var finishN = document.querySelector("#summary-region > div > div > div:nth-child(2) > div:nth-child(2) > p.small.clr-gray.summary-interest").innerHTML.split(" ")[6];

The whole text is:

textocompleto = document.querySelector("#summary-region > div > div > div:nth-child(2) > div:nth-child(2) > p.small.clr-gray.summary-interest");

I guess I have to use the .innerHTML but I dont know how to use it right. Anyone can help me?

Upvotes: 1

Views: 398

Answers (1)

Randy Casburn
Randy Casburn

Reputation: 14185

Doing this with JavaScript would look something like this:

const node = document.querySelector('p.summary-interest');
const span = document.querySelector('p.summary-interest span');
const text = node.childNodes[1].textContent;
newHTML = `${span.innerHTML}<b>${text}</b>`;
node.innerHTML = newHTML;
<p class="small clr-gray summary-interest" ing-unmask=""><span class="clr-black">10,39 % TIN</span> (10,90 % TAE)*</p>

Upvotes: 2

Related Questions