javascriptjquerycsswordpressvisual-composer

Give two elements with the same class a unique id


I am working in Wordpress with Visual Composer, and I have a toggle container. Essentially I click on each tab and the content below changes. I would like to assign a different image to each tab as a background, through css. I have achieved this however since each tab has the same class name (given to it by visual composer) the image is the same. I need to figure out how I can give each tab its own unique id, so that I can give each tab it's own background image - but since I can't edit the html directly, I think I need to do this with javascript. Does anyone know how I can achieve this? Here is the html code below:

<div class="vce-toggle-container-tab">
 <a class="vce-toggle-container-tab-title">Test 1</a>
</div>
<div class="vce-toggle-container-tab">
 <a class="vce-toggle-container-tab-title">Test 2</a>
</div>

And my css to add a background image:

a.vce-toggle-container-tab-title {
    background-image: url("https://katherinemade.com/staging/wp-content/uploads/2021/03/0I1A5234-3.jpg") !important;
    background-position: center;
    background-repeat: no-repeat;
    background-size: cover;
    width: 500px;
    height: 500px;
}

I hope I'm explaining this clearly. Please let me know if it's not understood and I will try again.


Solution

  • You can do it with nth-child or nth-of-type selectors without any need for js as follows

    a.vce-toggle-container-tab-title {
      background-position: center;
      background-position: center;
      background-repeat: no-repeat;
      background-size: cover;
      display: block;
      width: 100px;
      height: 100px;
    }
    
    .vce-toggle-container-tab:nth-of-type(1) a.vce-toggle-container-tab-title {
      background-image: url("https://via.placeholder.com/150?text=one") !important;
    }
    
    .vce-toggle-container-tab:nth-of-type(2) a.vce-toggle-container-tab-title {
      background-image: url("https://via.placeholder.com/150/0000FF/808080?text=two") !important;
    }
    
    .vce-toggle-container-tab:nth-of-type(3) a.vce-toggle-container-tab-title {
      background-image: url("https://via.placeholder.com/150?text=THREE") !important;
    }
    <div class="vce-toggle-container-tab">
      <a class="vce-toggle-container-tab-title">Test 1</a>
    </div>
    <div class="vce-toggle-container-tab">
      <a class="vce-toggle-container-tab-title">Test 2</a>
    </div>
    <div class="vce-toggle-container-tab">
      <a class="vce-toggle-container-tab-title">Test 3</a>
    </div>