Hello my friend i have the code below:
<div class='post-inner'> <span class='item_status'>Sold</span> <span class='item_status>Offer</span> </div>
and I want to change the background color for every text using javascript.
For example:
Detect Sold text using javascript then change the Red background color.
and
Detect Offer text using javascript then change the blue background color.
Thank you before
Advertisement
Answer
What we’re doing here is looping over all elements with class item_status checking the inner text if it contains the word then adding a class based on that
document.querySelectorAll('.item_status').forEach(i => { i.textContent.indexOf("Sold") !== -1 ? i.classList.add('red') : i.innerText.indexOf("Offer") !== -1 ? i.classList.add('green') : null; });
.red { color: red } .green { color: green; }
<div class='post-inner'> <span class='item_status'>Sold</span> <span class='item_status'>Offer</span> </div>