Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

216
Vistas
If Condition to check attribute's value

First of all, I am beginner in programming. I've got a question qbout JavaScript DOM. I would like to check if a tag or node has a backgroundColor style in order to execute the rest of the code, I also tried to put .clicked property but it doesn't work. Here's my code:

    let btn1 = document.getElementById("0");
    let btn2 = document.getElementById("1");
            
    btn1.addEventListener("click", function() {
        btn1.style.backgroundColor = 'red';
        btn2.style.backgroundColor = 'green';
    });

    if (btn1.style.background == 'red' || span2.style.backgroundColor == 'red') {
        console.log("test"); // doesn't work !!
    }
about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

It because your if statement only runs once. Wrap it inside a function and call that function after each click:

let span1 = document.getElementById("0").getElementsByTagName("span")[1];
let span2 = document.getElementById("0").getElementsByTagName("span")[2];

span1.addEventListener("click", function () {
    span1.style.backgroundColor = "gray";
    span2.style.backgroundColor = "#eee";
    checkColor();
});

span2.addEventListener("click", function () {
    span2.style.backgroundColor = "gray";
    span1.style.backgroundColor = "#eee";
    checkColor();
});

function checkColor() {
    if (
        span1.style.backgroundColor == "gray" ||
        span2.style.backgroundColor == "gray"
    ) {
        console.log("test"); // doesn't work !!
    }
}
<ul id="questions">
    <li id="0">
        <span>Do you like JavaScript?</span>
        <span>Yes</span><span>No</span><span class="result"></span>
    </li>
    <li id="1">
        <span>JavaScript and Java are the same</span>
        <span>Yes</span><span>No</span ><span class="result"></span>
    </li>
    <li id="2">
        <span>JavaScript is easy to learn</span>
        <span>Yes</span><span>No</span><span class="result"></span>
    </li>
</ul>

Note: this snippet only includes the first 2 spans.

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda