Soy nuevo en JavaScript. Quiero cambiar el color de fondo del elemento div que está en un bucle. En cada clic del elemento div, el color de fondo debe cambiar a color azul. He intentado usar CSS, funciona. Deseo implementarlo en Javascript. Quiero cambiar el color de fondo del div seleccionado. Pero mi código cambia el color de fondo del div seleccionado anteriormente y actualmente seleccionado.
Lo que he probado es:
Código ramita:
<div class="inbox_chat"> {% set newArray = [] %} {% for msg in msg_details %} {% if msg.to_name not in newArray %} <div class="chat_list active_chat" tabindex="{{loop.index}}" id="{{loop.index}}" onclick="viewMessage('{{loop.index}}')" > <div class="chat_people"> <div class="chat_img"> <img src="https://ptetutorials.com/images/user-profile.png" alt="sunil"> </div> <div class="chat_ib"> <h5>{{msg.to_name}} <span class="chat_date">{{msg.time}}</span></h5> </div> </div> </div> {% set newArray = newArray|merge([msg.to_name]) %} {% endif %} {% endfor %} </div>
Código JavaScript:
<script> function viewMessage(elementId) { var e = document.getElementById(elementId); var c= window.getComputedStyle(e).backgroundColor; if (c === "rgb(235, 235, 235)") { document.getElementById(elementId).style.backgroundColor = "blue"; } else { document.getElementById(elementId).style.backgroundColor = "rgb(235, 235, 235)"; } } </script>
Mi código cambia el color de fondo de los elementos div seleccionados actualmente y previamente seleccionados.
Cuál es mi salida:
¿Cómo cambiar el color de fondo del div seleccionado solo sin cambiar otro color de fondo div?
Debería usar getPropertyValue
para obtener el valor de una propiedad calculada:
function viewMessage(elementId) { var e = document.getElementById(elementId); var c = window.getComputedStyle(e).getPropertyValue('background-color'); if (c === "rgb(235, 235, 235)") { document.getElementById(elementId).style.backgroundColor = "blue"; } else { document.getElementById(elementId).style.backgroundColor = "rgb(235, 235, 235)"; } }