Issue
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 class="collection">
<ul class="list">
<li class="item"></li>
<div class="status">FREE
</div>
</li>
<li class="item"></li>
<div class="status">RESERVED
</div>
</li>
<li class="item"></li>
<div class="status">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>
Solution
// 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 class="collection">
<ul class="list">
<li class="item">
<div class="status">FREE
</div>
</li>
<li class="item">
<div class="status">RESERVED
</div>
</li>
<li class="item">
<div class="status">SOLD
</div>
</li>
</ul>
</div>
Answered By - Konrad Linkowski
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.