如何在所有元素上用`js`替换`no-js`类名? [英] How to replace the `no-js` class name by `js` on all elements?
问题描述
我想要做的是获取类名称为 no-js
的元素并将其替换为 js
.
What I’m trying to do is to get the elements with the class name no-js
and replace it with js
.
我不知道如何做到这一点.我试过谷歌搜索,但找不到任何东西,所以有人知道怎么做吗?
I have no idea how to do this. I tried Googling around but couldn’t find anything, so does anyone know how to do this?
我的目标是让菜单在点击时显示下拉导航,但如果 JavaScript 被禁用,我希望它在使用 CSS 悬停时显示(我已经这样做了).
My goal is to have a menu show a drop-down navigation when clicked, but if JavaScript is disabled I want it to show on hover with CSS (I’ve already done that).
我已将我的代码放在 JSFiddle 上.
I’ve put my code on JSFiddle.
推荐答案
您需要迭代返回的元素并替换每个元素上的那部分类名:
You need to iterate the returned elements and replace that portion of the class name on each one:
var els = [].slice.apply(document.getElementsByClassName("no-js"));
for (var i = 0; i < els.length; i++) {
els[i].className = els[i].className.replace(/ *\bno-js\b/g, "js");
}
请注意,getElementsByClassName
返回一个实时列表",这就是为什么需要首先复制返回值(使用 [].slice
)并进行迭代那个列表).
Note that getElementsByClassName
returns a "live list", which is why it's necessary to first make a copy of the return value (using [].slice
) and iterate that list instead).
这篇关于如何在所有元素上用`js`替换`no-js`类名?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!