Change all background color of <li> elements

I want to change the background of all list items. I have this, but it does not work.

// Get all <li> elements in the document
var x = document.querySelectorAll("li"); 

for (let i = 0; < x.length; i++;) {

x[i].style.backgroundColor = "red"; 
}
+4
source share
7 answers

using jquery, the next line will do the trick. $ ("Lee") CSS ("background color", "red") ;.

Hope this helps

0
source

Typo Error:

Replace for (let i = 0; < x.length; i++;)withfor (let i = 0; i < x.length; i++)

Another typo: ; afteri++

Your JS is correct, it just has a typo.

var x = document.querySelectorAll("li");

for (let i = 0; i < x.length; i++) {
  x[i].style.backgroundColor = "red";
}
li {
  color: white;
  text-align: center;
  border: 1px solid white;
  font-weight: 900;
}
<ul>
  <li>YOUR</li>
  <li>JAVASCRIPT</li>
  <li>IS</li>
  <li>WORKING</li>
</ul>
Run code
+5
source

:

var lists = document.getElementsByTagName("li");

// Var or Let works in the for loop

for(let list in lists) {
    lists[list].style.backgroundColor = "black";
}

jQuery, JavaScript

+2

, :

var x = document.querySelectorAll("li"); 

for (let i = 0; i < x.length; i++) {
    x[i].style.backgroundColor = "red"; 
}

:

x.forEach((li) => li.style.backgroundColor = "red");
+1

- css Javascript.

CSS

.red{
    background-color:red
}

JQuery

$('li').addClass('red')

jquery red li. , . .

$('ol.selected li').addClass('red')
.red{
        background-color:red
    }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<ol>
  <li>List item one</li>
  <li>List item two</li>
  <li>List item three</li>
</ol>

<ol class='selected'>
  <li>List item one</li>
  <li>List item two</li>
  <li>List item three</li>
</ol>
0

Array.
  from(document.getElementsByTagName("li"))
  .map(e => e.style.backgroundColor = "black");

[]
  .slice
  .call(document.getElementsByTagName("li"))
  .map(e => e.style.backgroundColor = "black");

forEach map .

P.S. , .

0

, forEach, .

let x = document.querySelector("li");
x.forEach(function(listElement){
this.style.background = "red";
]);

jquery. : a : ", , ".

, , -

0
source

Source: https://habr.com/ru/post/1695629/


All Articles