在Javascript中将id转换为类
如何将所有这些转换为所有div都有class而不是id? 我在这个世界上是新的,现在只是复制粘贴代码和学习在Javascript中将id转换为类,javascript,Javascript,如何将所有这些转换为所有div都有class而不是id? 我在这个世界上是新的,现在只是复制粘贴代码和学习 <div id="LEGEND">abB</div> <div id="small-a" style="display: none;">This is small-a</div> <div id="small-b" style="display: none;">This is small-b</div>
<div id="LEGEND">abB</div>
<div id="small-a" style="display: none;">This is small-a</div>
<div id="small-b" style="display: none;">This is small-b</div>
<div id="big-a" style="display: none;">This is big-a</div>
<div id="big-b" style="display: none;">This is big-b</div>
<script>
function showElement(id) {
document.getElementById(id).style.display = "block";
}
window.onload = function ShowHide() {
var legend = document.getElementById("LEGEND").innerHTML;
if(legend.indexOf("a") != -1) showElement("small-a");
if(legend.indexOf("b") != -1) showElement("small-b");
if(legend.indexOf("A") != -1) showElement("big-a");
if(legend.indexOf("B") != -1) showElement("big-b");
}
</script>
abB
这是小a
这是小b
这是个大问题
这是大b
函数showElement(id){
document.getElementById(id).style.display=“block”;
}
window.onload=函数ShowHide(){
var legend=document.getElementById(“legend”).innerHTML;
如果(图例索引(“a”)!=-1)showElement(“小a”);
如果(图例索引(“b”)!=-1)showElement(“小b”);
如果(图例索引(“A”)!=-1)showElement(“大A”);
如果(图例索引(“B”)!=-1)showElement(“大B”);
}
我不知道您为什么要以编程方式执行此操作,但无论如何:
const elements=document.querySelectorAll('div');
[…元素].forEach(el=>{
如果(标高id){
el.classList.add(el.id);
删除属性(“id”);
}
});代码>
.foo{
背景:番茄;
}
.酒吧{
背景:金;
}
巴兹先生{
背景:印度红;
}
Foo
酒吧
Baz
为什么要转换它?在记事本中打开文件。按Ctrl+H。在“查找内容”文本框中键入id=“
”。在“替换为”文本框中键入class=“
”。单击“全部替换”。关闭对话框并保存文件。将.textContent
放在.indexOf
之前。你没有带类的元素,你的第一句话也不清楚,所以我不确定你需要什么。我想看到与此相同的代码,但使用类而不是id,因为当我用类替换id时,事情不起作用。你为什么要转换它?甚至您的脚本也使用id,而不是类,因此当您更改属性时,它会中断。想知道如何代替函数showElement(id)使其与类相同吗