Each time the page loads, select the li list of default matching names
P粉155128211
P粉155128211 2023-08-13 17:51:12
0
1
549
<p>I created a list of color buttons on the product detail page on my e-commerce web page. When I enter the page I want the matching color li button to be selected by default. A specific color name (text string) is available on each product page. Below is a summary of my code. </p> <pre class="brush:php;toolbar:false;"><div class="color-wrap"> <ul> <li class="text"><a href="/link.." class="ivory" ></a></li> <li class="text"><a href="/link.." class="beige"></a></li> <li class="text selected"><a href="/link.." class="green"></a></li> <li class="text"><a href="/link.." class="blue"></a></li> </ul> </div> <style> .color-wrap {} .color-wrap li a {} .color-wrap li.selected a {border-color:red;} .color-wrap .ivory {#fff;} .color-wrap .beige {#eee;} .color-wrap .green {green;} .color-wrap .blue {blue;} </style></pre> <p>My idea is to use JavaScript to find/search/match the color name in the class name of the "a" tag and force the class "selected" to be added to the li. As you can see, the button name should be identified by its "a" tag rather than its "li" tag. I know next to nothing about coding. </p> <p>I looked at all similar stackoverflow threads but couldn't find a solution. Please help me:(</p> <p>So far, I have tried the match, find, and filter functions, but they all failed. </p>
P粉155128211
P粉155128211

reply all(1)
P粉032900484

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>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template