Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

210
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!