0

我有一个 id 为的 div,divId并且我编写了一个 JS 脚本,通过它我突出显示了“this”关键字。
这是JS代码

            var regex = new RegExp('this',"gi");
     document.getElementById("divId").innerHTML=document.getElementById("divId").
    innerHTML.replace(regex, function(matched) 
{return '<span class=\'highlight\'>' + matched + '</span>';})

这是div

This is the text This is the text This is the text This is the text 
This is the text This is the text This is the text This is the text 
This is the text This is the text This is the text This is the text 

现在我想创建一个按钮,单击该按钮并highlight删除了类。我已经尝试过,document.getElementById("divId").className = ""但是没有用。因为我是 JS 新手,所以现在经过我的努力,现在我将这个问题传递给 SO 专家。如何我可以从thisdiv 中的所有单词中删除类有
什么建议吗?

4

3 回答 3

3

较新的浏览器(IE8+ 等)上,您可以这样做:

var list = document.querySelectorAll("#divId span.highlight");
var index;
for (index = 0; index < list.length; ++index) {
    list[index].className = "";
}

在较旧的浏览器上,您可以这样做:

var list = document.getElementById("divId").getElementsByTagName("span");
var index;
for (index = 0; index < list.length; ++index) {
    if (list[index].className === "highlight") {
        list[index].className = "";
    }
}

在这两种情况下,我都假设“highlight”是这些跨度上的唯一类。

于 2013-07-02T08:24:13.867 回答
1

如果您使用或愿意在您的页面上包含 jquery,您可以这样做:

$('#divId span').removeClass('highlight');

好的是其他类没有被删除。

其他js-frameworks中也有类似的功能,比如prototype.js

于 2013-07-02T08:29:37.453 回答
0

尝试这个:

var div = document.getElementById("divId");
var divs = div.getElementsByTagName('span')
for (var i=0; i<divs.length;i++){
divs[i].className  = '';
}

或者

document.getElementById("theButton").onclick = function() {
var regex = new RegExp('<span class="highlight">this</span>','gi');
var div = document.getElementById("divId");
div.innerHTML = div.innerHTML.replace(regex,"this");
于 2013-07-02T08:22:53.520 回答