Home > Net >  How to add background color to the test in webpage?
How to add background color to the test in webpage?

Time:05-14

I found some text in webpage using below code

document.body.innerText.indexOf('tested')
document.body.innerText.includes('tested')

after finding the text I want to apply background color to that text.

CodePudding user response:

Find the reference of the element with your innerText:

let xpath = "//div[text()='tested']";
let element = document.evaluate(xpath, document, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue;

Replace div with whatever type of element you have where the text is present

You can directly change the style once you have the element reference:

element.style.backgroundColor = "red";

  • Related