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>
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>
CodePudding user response:
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>
<iframe name="sif2" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>