Home > Software engineering >  Change background color according to the text contained between the tags
Change background color according to the text contained between the tags

Time:10-15

I need help to develop a function to test if the value contained between two div tags (of a specific class) is equal to a character string.

I then need to wrap it in a loop that does this across my entire page on load.

Then I need to add it inside a loop for every article.

Do you know how can i do this?

function changeBackgroundColor() {
  var text = document.getElementsByClassName("disponibilite_mh")[0].innerText;
  const bg_defaut = document.getElementsByClassName("disponibilite_mh")[0].style.backgroundColor = 'white';
  switch (text) {
    case 'Available':

      document.getElementsByClassName("disponibilite_mh")[0].style.backgroundColor = 'green';

      break;

    case 'Reserved':
      document.getElementsByClassName("disponibilite_mh")[0].style.backgroundColor = 'orange';

      break;

    case 'Selled':
      document.getElementsByClassName("disponibilite_mh")[0].style.backgroundColor = 'red';
      break;
    default:
  }
}
window.onload = changeBackgroundColor;
<div >Available</div>

CodePudding user response:

This should solve your problem.

function changeBackgroundColor() {
    const elements = document.getElementsByClassName("disponibilite_mh");
    for (let element of elements) {
        switch (element.innerText) {
            case 'Available':
                element.style.backgroundColor = 'green';
                break;
            case 'Reserved':
                element.style.backgroundColor = 'orange';
                break;
            case 'Selled':
                element.style.backgroundColor = 'red';
                break;
            default:
                element.style.backgroundColor = 'white';
        } 
    }
}
window.onload = changeBackgroundColor;

CodePudding user response:

Please cache the element. Stay DRY

Or better, loop and only set the color value in the switch:

const changeBackgroundColor = () => {
  document.querySelectorAll(".disponibilite_mh").forEach(disp => {
    const text = disp.innerText.trim();
    switch (text) {
      case 'Available':
        color = 'green';
        break;
      case 'Reserved':
        color = 'orange';
        break;
      case 'Selled':
        color = 'red';
        break;
      default:
        color = 'white'
    }
    console.log(text,color)
    disp.style.backgroundColor = color;
  })
}
window.addEventListener("DOMContentLoaded", changeBackgroundColor);
<div >Available</div>
<div >Reserved</div>
<div >Selled</div>

  • Related