首页 > 解决方案 > 选择随机元素并设置属性背景颜色

问题描述

如何为 ID 为“hello”的随机元素赋予红色?

<h1 id="hello">a</h1> <h1 id="hello">b</h1> <h1 id="hello">c</h1>

标签: javascriptcssrandom

解决方案


当您使用 class 而不是 id 时,您可以执行类似的操作。

  • 获取所有 hello 元素
  • 在从零到元素长度的范围内创建一个随机索引
  • 将 helloElements 中这个随机索引元素的 style.color 设置为红色

let helloElements = document.querySelectorAll(".hello");


let ind = (Math.floor(Math.random() * helloElements.length))
console.log(ind);
helloElements[ind].style.color = "red";
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<h1 class="hello">a</h1> <h1 class="hello">b</h1> <h1 class="hello">c</h1>


推荐阅读