javascriptfor-loopclassname

I want to call and modify the element that I want to choose in same classes


I don't know how to call the single or any element in same classes like if p.innerHTML == null then the background of div will change or make any code. The only thing I know is getting a document by ClassName and call the element through [0], [1], [2], [3], ... and so on.. But it mades a lots of codes as the div is many. Is there any code to make the code shorter?

<!DOCTYPE html>
<html lang="en">
<head>
   <meta charset="UTF-8">
   <title>Page title</title>
   <meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
   <div class="box">
<p class="ppp">Philippines</p>
   </div>
   <div class="box">
<p class="ppp">Singapore</p>
   </div>
   <div class="box">
<p class="ppp">null</p>
   </div>
   <div class="box">
<p class="ppp">Japan</p>
   </div>
   <div class="box">
<p class="ppp">null</p>
   </div>
</body>
</html>

<style>
*{
margin: 0;
padding: 0;
}
body{
   display: flex;
   flex-direction: column;
   height: 100vh;
   width: 100%;
   justify-content: center;
   align-items: center;
}
div{
   width: 50%;
   background: blue;
   color: white;
   font-size: 22px;
   padding: 10px;
   border-radius: 8px;
   margin: 5px 0;
   text-align: center;
}
@media (min-width: 600px){
body{
   flex-direction: row;
   gap: 10px;
}
div{
   font-size: 30px;
   padding: 15px;
}
}
</style>

<script>
var a = document.getElementsByClassName("box");
var b = document.getElementsByClassName("ppp");

if(b[0].innerHTML == "null"){
a[0].style.background = "red";
}
if(b[1].innerHTML == "null"){
a[1].style.background = "red";
}
if(b[2].innerHTML == "null"){
a[2].style.background = "red";
}
if(b[3].innerHTML == "null"){
a[3].style.background = "red";
}
if(b[4].innerHTML == "null"){
a[4].style.background = "red";
}

</script>

The code above is perfectly working but there's a lot of code in Javascript. What if I make 20 div? So that the code is extend as the div extend also.

The only problem for this is to make the code shorter. I use

for(let i = 0; ppp.length > i; i++){
if(ppp[i].innerHTML == "null"){
this.style.background = "red";
}

}

But it's not working....


Solution

  • Can you try

    for(let i = 0; box.length > i; i++){
      if(box[i].innerHTML == "null"){
        box[i].style.background = "red";
      }
    }
    

    Or you can use a functional programing manner, and make it a function that's has better readability

    function highlightNullBoxes(boxes) {
      Array.from(boxes)
        .filter((el) => el.innerHTML === "null")
        .forEach((el) => {
          el.style.background = "red";
        });
    }
    
    // You can simply call this 
    var a = document.getElementsByClassName("box");
    highlightNullBoxes(a);