Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/466.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 将类添加到类列表中_Javascript - Fatal编程技术网

Javascript 将类添加到类列表中

Javascript 将类添加到类列表中,javascript,Javascript,我正在尝试将一个类添加到类列表中。我试过使用 document.getElementById('sectionRowTitles').className += "sectionFieldRating" 以及 document.getElementById('sectionRowTitles').setAttribute("class", document.getElementById('sectionRowTitles').getAttribute("class") + "sectionFie

我正在尝试将一个类添加到类列表中。我试过使用

document.getElementById('sectionRowTitles').className += "sectionFieldRating"
以及

document.getElementById('sectionRowTitles').setAttribute("class", document.getElementById('sectionRowTitles').getAttribute("class") + "sectionFieldRating")
而且

var sectionFieldRating = document.createElement('div');
document.getElementById('sectionRowTitles').appendChild('sectionFieldRating');
HTML看起来像

课程 教练 方法 您可以使用:


classList在所有现代浏览器和IE10+中都可用。

classList在所有现代浏览器中都可用,如果出于某种原因,您正在为可以使用的古代浏览器编码


el.setAttributeclass,el.getAttributeclass++newclass

您在标题中有它,但在代码中没有。您没有解释您遇到的问题。换句话说,到底发生了什么你没有预料到的事情?你以为会发生什么?您所展示的内容存在明显的问题,但它们可能不是您试图解决的问题,因为您没有描述您的问题是什么。如前所述,这似乎与Chrome扩展无关。您直接操作的是类列表。class属性是一个以空格分隔的列表。您正在尝试添加一个类,而不使用空格将其与任何其他已存在的类分隔开。这样做会导致您的新类和列表中的最后一个类都无法按预期的方式工作。使这种操作更容易是存在的原因。鉴于您是为Chrome扩展而开发的,因此不需要与Chrome以外的任何东西兼容。因此,使用它。可能的重复将它添加到Id中,而不是我不理解的类列表中-您的注释显示一个包含2个类的div,包括新添加的一个类。这就是您想要的输出吗?我想在div列表中添加一个新div,如上所述。我犯了错误,我意识到这不是我所要求的。
document.getElementById('sectionRowTitles').classList.add("sectionFieldRating");