Home > Net >  apply css by checking if value exists
apply css by checking if value exists

Time:07-06

I have an array with objects inside. What I'm trying to do is loop through the array and check if a value exists by key and if it does apply a CSS to a div but right now even though the value exists the specified CSS doesn't apply it just applies the "else" CSS. Why is this happening and how can I fix it? Thanks in advance.

let testArray = [{"length": "None", "duration": "10000", "percentage": "65"}, {"width": "Half", "detail": "under", "duration": "25000", "percentage": "25"}, {"length": "Full", "duration": "20000", "percentage": "90"}]

testArray.forEach((obj) => {
  if (obj.length?.toLowerCase() == 'none') {
    $('.test').css('background-color', 'red')
  } else {
    $('.test').css('background-color', 'blue')
  }
});
.test {
  width: 30%;
  height: 40%;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class='test'>
  <p>testing</p>
</div>

CodePudding user response:

It's changing to red as the first value is equal to none but the next two values are not equal to none so it's changed back to blue twice.If you don't want this then you could break out of the loop at this point.

    let testArray = [{"length": "None", "duration": "10000", "percentage": "65"}, {"width": "Half", "detail": "under", "duration": "25000", "percentage": "25"}, {"length": "Full", "duration": "20000", "percentage": "90"}]

        testArray.every((obj) => {
          if (obj.length?.toLowerCase() == 'none') {
            $('.test').css('background-color', 'red')
            return false;
          } else {
            $('.test').css('background-color', 'blue')
          }
          return false;
        });
   .test {
          width: 30%;
          height: 40%;
        }
        <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
        <div class='test'>
          <p>testing</p>
        </div>

CodePudding user response:

The easiest way on this case is use a frontent framework, like react, handlebars, etc..

The think is, on these frameworks you will render your code depending in the result, like this for react: (note that this is directly on the HTML)

{testArray.map(()=>{
  (obj.length?.toLowerCase() == 'none' )
  ? <div>Some info</div>
  : <div>Some different info</div>
})}

  • Related