P粉0329004842023-08-14 10:40:06
You can use the document.querySelector
method to find elements by class name.
The code below assumes that the "specific color name" is stored in a variable named selectedColor
. It also makes some corrections to your <style>
elements. You can try my code to compare with yours to see the difference.
const selectedColor = "green"; document.querySelector(".color-wrap a." + selectedColor).parentNode.classList.add("selected");
.color-wrap {} .color-wrap li a {} .color-wrap li.selected a {border: red 1px solid;} .color-wrap .ivory {color: #fff;} .color-wrap .beige {color: #eee;} .color-wrap .green {color: green;} .color-wrap .blue {color: blue;}
<div class="color-wrap"> <ul> <li class="text"><a href="/link.." class="ivory">Ivory</a></li> <li class="text"><a href="/link.." class="beige">Beige</a></li> <li class="text"><a href="/link.." class="green">Green</a></li> <li class="text"><a href="/link.." class="blue">Blue</a></li> </ul> </div>