default matching name selected on li list every page load

46 views Asked by At

I have a list of color buttons created for the product detail page on my ecommerce webpage. When I enter the page, I would like the matching color li button to be selected by default. There is a specific color name (text string) available to use on every product page. Here is summary of my code.

<div id="colorList">
<!--//bring in other page element-->
<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>
<!--//bring in other page element-->
</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>


<script type="text/javascript">
$(document).ready(function(){
$("#colorList").load("/product/t-shirt01.html .color-wrap");

const selectedColor = "green"; 
document.querySelector(".color-wrap a." + selectedColor).parentNode.classList.add("selected");
});
</script>

My ideas is to use javascript and let it find/search/match the color name among the class name of the 'a' tags.. and force to add class "selected" to the li? As you can see button name should be recognized by its 'a' tag not the 'li'. I barely have knowledge in coding.

I look through all stackoverflow threads similar to this but couldn't find the solution. please help:(

So far I tried match, find, filter functions but I failed all.

1

There are 1 answers

1
Heiko Theißen On

You can look up an element by its class name with the document.querySelector method.

The code below assumes that the "specific color name" is in a variable called selectedColor. It also makes some corrections to your <style> element. You should try out my code compared to your code in order 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>