• Jobs
  • About Us
  • professionals
    • Home
    • Jobs
    • Courses and challenges
  • business
    • Home
    • Post vacancy
    • Our process
    • Pricing
    • Assessments
    • Payroll
    • Blog
    • Sales
    • Salary Calculator

0

421
Views
Cómo cambiar el color de fondo de div en bucle en ramita usando javascript

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:

Producción

¿Cómo cambiar el color de fondo del div seleccionado solo sin cambiar otro color de fondo div?

almost 3 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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)"; } }
almost 3 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Our process Sales
Legal
Terms and conditions Privacy policy
© 2025 PeakU Inc. All Rights Reserved.

Andres GPT

Recommend me some offers
I have an error