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

110
Views
How to have default and remove class on Ul li using vanilla JavaScript?

I have two ul with the same class, the concept I tried to achieve is when clicking the active li should have border color change. I have succeeded in that, the concept I need is I want to have the default same border color present on first ul li, and if I click other it should get removed and color should apply on clicked one. The code I have tried so far.

Any help will be appreciated !!

var x = document.querySelectorAll('.random-value li');
for (var i = 0; i < x.length; i++) {
    x[i].addEventListener("click", function() {

        var selectedEl = document.querySelector(".selected");
        if (selectedEl) {

            selectedEl.classList.remove("selected");
        }
        this.classList.add("selected");

    }, false);
};
.random-value li{
        margin: 0 0 15px 0;
        border: 1px solid green;
        padding: 15px 26px;
    }
    .random-value .selected{
     border: 1px solid red;
    }
<ul id="first" class="random-value">
<li>200 </li>
<li>2010 </li>
<li>2100 </li>
<li>2030 </li>
</ul>

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

I think this is what you are looking for,

//Making first option as Highlighted
document.querySelectorAll('.random-value li')[0].classList.add("selected"); 

var x = document.querySelectorAll('.random-value li');
for (var i = 0; i < x.length; i++) {
    x[i].addEventListener("click", function() {

        var selectedEl = document.querySelector(".selected");
        if (selectedEl) {

            selectedEl.classList.remove("selected");
        }
        this.classList.add("selected");

    }, false);
};
.random-value li{
        margin: 0 0 15px 0;
        border: 1px solid green;
        padding: 15px 26px;
    }
    .random-value .selected{
     border: 1px solid red;
    }
<ul id="first" class="random-value">
<li>200 </li>
<li>2010 </li>
<li>2100 </li>
<li>2030 </li>
</ul>

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!