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.
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!