SCSOName SCSOName - 3 months ago 9
HTML Question

How to make every `<li>` with different background colors?

How to make every

<li>
with different background colors?

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<div id="dvi1" class="div1">
<ul id="ul" class="ul">
<li>11</li>
<li>22</li>
<li>33</li>
<li>44</li>
</ul>
</div>
</body>
</html>

Answer

This is an example where i iterate through all li elements in your document and changing their background color. I predefined colors and after that I'm just using Math.random() to get random color from given array.

$('li').each(function() {
  var back = ["green","blue","gray","yellow","orange","purple","black"];
  var rand = back[Math.floor(Math.random() * back.length)];
  $(this).css('background',rand);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<!DOCTYPE html>
<html lang="en">
   <head>
<meta charset="UTF-8">
<title>Title</title>
 </head>
<body>
 <div id="dvi1" class="div1">
    <ul id="ul" class="ul">
      <li>11</li>
      <li>22</li>
      <li>33</li>
      <li>44</li>
   </ul>
</div>
</body>
</html>

Comments