Home >Web Front-end >JS Tutorial >How to change background color with javascript

How to change background color with javascript

醉折花枝作酒筹
醉折花枝作酒筹Original
2021-06-15 10:45:393770browse

In JavaScript, you can use the style object attribute to change the background color. The syntax format is "element object.style.background="color value"". The Style object represents a single style declaration and can be accessed from the document or element to which the style is applied.

How to change background color with javascript

The operating environment of this tutorial: windows7 system, javascript version 1.8.5, Dell G3 computer.

<html>
  <head></head>
  <body>
    <ul id="ul1">
      <li></li>
      <li></li>
      <li></li>
      <li class="box"></li>
      <li></li>
      <li class="box"></li>
      <li class="box"></li>
      <li></li>
      <li></li>
      <li></li>
    </ul>
  </body>
</html>
<script>
  window.onload = function () {
    //获取名字ul1的ID
    var oUl = document.getElementById("ul1");
    //获取li标签
    var aLi = oUl.getElementsByTagName("li");
    //循环li
    for (var i = 0; i < aLi.length; i++) {
      //判断li标签名字为className为box
      if (aLi[i].className == "box") {
        //给li标签加背景色
        aLi[i].style.background = "red";
      }
    }
  };
</script>

[Recommended learning: javascript advanced tutorial]

The above is the detailed content of How to change background color with javascript. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn