search.length 有没有办法从段落中检索文本并更改其颜色?

我试过:

<p id="userInput">1,2,3,4,5,6,7,some text,another text</p>

 var qq = document.getElementById("userInput").innerHTML.match(/5/g);
 var blaaa = qq.style.color = "red";
 document.getElementById("userInput").innerHTML = blaaa;

编辑:
var search = ['new', 'and'];
$(document).ready(function () {
    for(var i = 0;i<2;i++){
    $("div:contains('"+search[i]+"')").each(function () {
        var regex = new RegExp(search[i],'gi');
        $(this).html($(this).text().replace(regex, "<span class='red'>"+search[i]+"</span>"));
    });
    }
});

最佳答案

不,没有,除非您将文本包装在它自己的元素中,例如跨度

var el = document.getElementById("userInput");

el.innerHTML = el.innerHTML.replace(/(5)/g, '<span style="color: red">$1</span>');
<p id="userInput">1,2,3,4,5,6,7,some text,another text</p>

关于javascript - 从段落中检索文本并更改其颜色,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/27054983/

10-12 12:38
查看更多