4 回答
TA贡献1862条经验 获得超6个赞
您可以搜索子字符串“FREE”并将其替换为样式化 HTML。如果“FREE”在字符串中出现多次,您可能需要使用正则表达式(除非您不需要支持 Internet Explorer)。
在你的情况下:
let str = '<h1 id="headline">"FREE floss set and dentures!"</h1>' str = str.replace(/FREE/g, '<span color="red">FREE</span>');
TA贡献1893条经验 获得超10个赞
这是一个使用切片和一些经典串联的工作示例。
编辑:现在还包括第二个字符串的代码。
//get headline by id
var headline = document.getElementById("headline");
//declare your possible strings in vars
var string1 = "Get your FREE toothbrush!"
var string2 = "FREE floss set and dentures!"
//declare formatted span with "FREE" in var
var formattedFree = "<span style='color: blue; font-style: italic;'>FREE</span>"
//target positions for the rest of your string
var string1Position = 13
var string2Position = 4
//concat your vars into expected positions for each string
var newString1 = string1.slice(0, 9) + formattedFree + string1.slice(string1Position);
var newString2 = formattedFree + string2.slice(string2Position)
//check if strings exist in html, if they do then append the new strings with formatted span
if (headline.innerHTML.includes(string1)) {
headline.innerHTML = newString1
}
else if (headline.innerHTML.includes(string2)) {
headline.innerHTML = newString2
}
<!-- As you can see the original string does not have "FREE" formatted -->
<!-- Change this to your other string "FREE floss set and dentures!" to see it work there as well -->
<h1 id="headline">Get your FREE toothbrush!</h1>
TA贡献1817条经验 获得超14个赞
您要查找的属性是innerHTML,请查看以下示例:
var word = document.getElementById('word');
function changeWord(){
word.innerHTML = "another";
word.style.backgroundColor = 'black';
word.style.color = 'white';
}
<h1 id="headline">
<span id="word">some</span> base title
</h1>
<button onClick="changeWord()">
change
</button>
TA贡献1801条经验 获得超8个赞
您可以拆分文本并将关键字“FREE”转换为 span 元素。因此您可以设置关键字“FREE”的样式。此方法是安全的,因为不会更改任何非文本 html 元素。
var keyword = "FREE";
var headline = document.getElementById("headline");
var highlight, index;
headline.childNodes.forEach(child => {
if (child.nodeType == Node.TEXT_NODE) {
while ((index = child.textContent.indexOf(keyword)) != -1) {
highlight = child.splitText(index);
child = highlight.splitText(keyword.length);
with(headline.insertBefore(document.createElement("span"), highlight)) {
appendChild(highlight);
className = 'highlight';
}
}
}
});
.highlight {
/* style your keyword */
background-color: yellow;
}
<div id="FREE">
<h1 id="headline">"Get your FREE toothbrush! FREE floss set and dentures!"</h1>
</div>
添加回答
举报