Change color of an element based on the text in it

1598 views javascript
5

I need to change color of an element based on the text in it. For example if the text in the div with id greenStock is In Stock the color of In Stock should be green. else default color.

<html>

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

<script>

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

//alert(textColor);

if (textColor === 'In Stock'){

    textColor.style.color = "#048f00";
}

</script>
</html>

answered question

textColor is a string, not an element. It doesn’t have a style property; document.getElementById('greenStock') does.

2 Answers

9

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>
    </body>
    
    <script>
    
    let element = document.getElementById('greenStock');
    var textColor = element.innerHTML;
    
    
    
    if (textColor === 'In Stock'){
    	element.style.color = "red";
    }
    
    </script>
    </html>

posted this
11

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>

posted this

Have an answer?

JD

Please login first before posting an answer.