根据元素中的文本更改元素的颜色

时间:2018-11-08 14:51:46

标签: javascript

评论:我有一个带有状态的动态产品列表。该代码仅作用于第一个,而另一个则不会使“有货”颜色变为红色?

<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>

2 个答案:

答案 0 :(得分:1)

textColor是元素的innerHTML,属性style仅存在于元素上,而不存在于元素的innerHTML上。

这应该有效

<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>

答案 1 :(得分:0)

<section class="palm-section text-center" id="palm-section">
    <div class="palm-img">
        <h1>Palm Hotel</h1>
        <div class="break-line"></div>
    </div>
</section>
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"