我想以编程方式更改 HTML 段落中单个单词的样式
let textToSearch = "testing"
let beforeNode = document.createElement('p');
let afterNode = document.createElement('p');
let highlightedSpan = document.createElement('span')
highlightedSpan.innerHTML = textToSearch;
highlightedSpan.style.backgroundColor = "yellow"
let newPar = document.createElement('p');
newPar.appendChild(highlightedSpan);
document.querySelectorAll('p').forEach((par) => {
let cont = par.textContent;
let startingPos = cont.indexOf(textToSearch)
console.log(startingPos)
if (startingPos !== -1) {
let firstPart = cont.slice(0, startingPos - 1)
let thirdPart = cont.slice(startingPos + textToSearch.length, cont.length - 1)
beforeNode.appendChild(document.createTextNode(firstPart))
afterNode.appendChild(document.createTextNode(thirdPart))
par.replaceWith(beforeNode, highlightedSpan, afterNode)
}
})
<p> A complete text for testing purposes</p>
我得到这个输出:
但我想了解是否有一种视觉上更好(现在文本内容在视觉上分布在三行)、更清晰的方法来更改 HTML 段落的单个单词的样式
只需使用正则表达式将单词替换为包含在跨度中的单词: