Home > database >  How to add a condition in Javastript for changing the font color depending on the displayed text
How to add a condition in Javastript for changing the font color depending on the displayed text

Time:10-21

im new in JS. How to add font color dependency based on displayed text in Javascript?

There may be several statuses on the displayed page (FREE, RESERVED, SOLD), I would like the dependency to work on any number of displayed statuses on the page. Tried to get innerText and textContent to display in console, but the fetch only works for single document.querySelector and not document.querySelectorAll here the console displays undefined but in Nodelist in console.log is correct (3), and the innerText in individual nodes displays correctly: first is FREE, second is RESERVED, and third is SOLD

<div >
  <ul >
   <li ></li>
    <div >FREE
    </div>
   </li>
   <li ></li>
    <div >RESERVED
    </div>
   </li>
   <li ></li>
    <div >SOLD
    </div>
   </li>
  </ul>
</div>

<script>
  var status = document.querySelectorAll('.status');

  // Nodelist in console.log is correct (3), and the innerText in individual nodes displays correctly: first is FREE, second is RESERVED, and third is SOLD
 
  // How to add font color dependency based on innerText??
  // status FREE with green color font
  // status RESERVED with orange color font
  // status SOLD with redcolor font

</script>

CodePudding user response:

// get all statuses
const statuses = document.querySelectorAll('.status')

// define a color for each status
const colors = {
  FREE: 'yellow',
  RESERVED: 'blue',
  SOLD: 'red'
}

statuses.forEach(status => {
  // get timmed text
  const text = status.textContent.trim()
  // get the color
  const color = colors[text]
  // set the color
  status.style.color = color
})
<div >
  <ul >
    <li >
      <div >FREE
      </div>
    </li>
    <li >
      <div >RESERVED
      </div>
    </li>
    <li >
      <div >SOLD
      </div>
    </li>
  </ul>
</div>

  • Related