Javascript DOM <UL> set list item background
<!DOCTYPE html> <head> <script> window.onload=function() {/*from w w w . j av a 2s . c o m*/ document.getElementById("pink").onclick=paintPink; document.getElementById("blue").onclick=paintBlue; document.getElementById("green").onclick=paintGreen; } function paintPink() { try { let lis = document.querySelectorAll('li:nth-child(2n+1)'); for (let i = 0; i < lis.length; i++) { lis[i].setAttribute("style","background-color: #ffeeee"); } } catch(e) { console.log("Doesn't work in this browser"); } } function paintBlue() { try { let lis = document.querySelectorAll('li:nth-child(odd)'); for (let i = 0; i < lis.length; i++) { lis[i].setAttribute("style","background-color: #eeeeff"); } } catch(e) { console.log("Doesn't work in this browser"); } } function paintGreen() { let parentElement = document.getElementById("thelist"); let lis = parentElement.getElementsByTagName("li"); for (let i = 0; i < lis.length; i++) { if (i % 2 == 0) { lis[i].setAttribute("style","background-color: #eeffee"); } } } </script> </head> <body> <div> <button id="pink">Pink Stripes</button> <button id="blue">Blue Stripes</button> <button id="green">Green Stripes</button> </div> <ul id="thelist"> <li>Go</li> <li>C++</li> <li>CSS</li> <li>HTML</li> <li>Java</li> <li>Python</li> </ul> </body> </html>