在Javascript中将id转换为class

时间:2016-09-07 17:11:58

标签: javascript

如何转换所有这些所有div都有类而不是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="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>

1 个答案:

答案 0 :(得分:0)

我不知道你为什么要以编程方式进行此操作,但无论如何:

const elements = document.querySelectorAll('div');

[...elements].forEach(el => {
  if (el.id) {
    el.classList.add(el.id);
    el.removeAttribute('id');
  }
});
.foo {
  background: tomato;
}

.bar {
  background: gold;
}

.baz {
  background: indianred;
}
<div id="foo">Foo</div>
<div id="bar">Bar</div>
<div id="baz">Baz</div>