javascript - 循环遍历具有特定样式的所有元素

标签 javascript html css

如果我在页面上有一堆带有 background-color: #000685; 的元素没有共同点(没有共同的 id、类、标签名称等)。
有没有办法用 JavaScript 遍历它们并更改背景颜色值?

最佳答案

由于这些元素没有任何共同点,您能做的最好的事情就是遍历页面上的每个元素,获取每个元素的背景颜色,然后执行检查。像这样:

var elements = document.getElementsByTagName("*");
for(let i = 0; i < elements.length; i++){
  var cur = elements[i];
  if(cur.style.backgroundColor=="rgb(0, 6, 133)"){
    cur.style.backgroundColor="red";
  }
}
<div style="background-color: #000685;">I should be red</div>
<div>I should not be red.</div>
<div style="background-color: #000685;">I should be red</div>
<div style="background-color: #000685;">I should be red</div>
<div>I should not be red.</div>
<div>I should not be red.</div>
<p style="background-color: #000685;">I should be red</p>
<p>I should not be red.</p>

如果样式不是内联样式,请使用 getComputedStyle().getPropertyValue("background-color") :

var elements = document.getElementsByTagName("*");
for(let i = 0; i < elements.length; i++){
  var cur = elements[i];
  if(window.getComputedStyle(cur).getPropertyValue("background-color")=="rgb(0, 6, 133)"){
    cur.style.backgroundColor="red";
  }
}
.one{
  background-color: #000685;
}
.two{
  background-color: #000685;
}
.three{
  background-color:black;
  color:white;
}
<div class="one">I should be red</div>
<div>I should not be red.</div>
<div class="two">I should be red</div>
<div class="one">I should be red</div>
<div class="three">I should not be red.</div>
<div>I should not be red.</div>
<p class="two">I should be red</p>
<p class="three">I should not be red.</p>

关于javascript - 循环遍历具有特定样式的所有元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67362621/

相关文章:

jquery - CSS Accordion 菜单,在 IE Quirks 模式下不起作用

javascript - 在该元素和其他元素上点击和鼠标输入/鼠标离开时动画元素

html - Mat Select 多个设置选定值

html - 更改 bootstrap 3 中的堆叠顺序

javascript - 在 Meteor.js 中填写向导表单后创建用户

javascript - 如何通过 javascript/AJAX 使用 reqres.in 中的数据

javascript - 对我的 HTML 输入文本求和不起作用

jquery - 在单选按钮选择上切换背景颜色

javascript - 如何使用旋转找出旋转梯形的边界框

javascript - Ajax 数据与日期选择器事件不同步