Sukhpreet Singh Alang
Sukhpreet Singh Alang

Reputation: 37

Change color of an element based on the text in it

Comment: I have a dynamic list of products with status. the code just acts on the first one and for the other it does not make the In Stock color red?

<body>
<div id="greenStock" class="zcd-status">In Stock</div>
<div id="greenStock" class="zcd-status">Available</div>
<div id="greenStock" class="zcd-status">In Stock</div>
<div id="greenStock" class="zcd-status">In Stock</div>

</body>

<script>

let element = document.getElementById('greenStock');
var textColor = element.innerHTML;



if (textColor === 'In Stock'){
    element.style.color = "red";
}

</script>
</html>

Upvotes: 0

Views: 58

Answers (2)

mika
mika

Reputation: 343

textColor is the innerHTML of the element and the property style only exists on the element not on the innerHTML of the element.

This should work

<html>
    
    <body>
    <div id="greenStock" class="zcd-status">In Stock</div>
    <div id="greenStock" class="zcd-status">Available</div>
    <div id="greenStock" class="zcd-status">In Stock</div>
    <div id="greenStock" class="zcd-status">In Stock</div>
    </body>
    
    <script>
    
    let element = document.getElementById('greenStock');
    var textColor = element.innerHTML;
    
    
    
    if (textColor === 'In Stock'){
    	element.style.color = "red";
    }
    
    </script>
    </html>

Upvotes: 1

Transformer
Transformer

Reputation: 3760

var textColor = document.getElementById('greenStock').innerHTML;

//alert(textColor);

if (textColor == 'In Stock'){

    document.getElementById('greenStock').style.color = "#048f00";
} else {
    document.getElementById('greenStock').style.color = "any other color"
<html>

<body>
<div id="greenStock" class="zcd-status">In Stock</div>
</body>
</html>

Upvotes: 0

Related Questions