1

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>

3
  • It seems to work.
    – Sean
    Commented Oct 28, 2021 at 17:01
  • I want first one to be default selected, ex 185 should have border color red and after that my current scenario should happen.
    – Kumar
    Commented Oct 28, 2021 at 17:02
  • add class="selected" to the first li in your html then run the same code and if I understand the question correctly it would work Commented Oct 28, 2021 at 17:24

1 Answer 1

1

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>

Not the answer you're looking for? Browse other questions tagged or ask your own question.