skip to Main Content

I’m calling a function on Click event to add a CSS class to an item in the list of elements with same class name.

Here’s what I’m trying to achieve
On the click of the button, I want to add the class .active to a particular logo image. Let’s say at index 0 or 1

Please help me fix the issue.

document.ready(function() {
  function setActive() {
    $(".logo-slider .logos .logo")[0].addClass("active");
  }
})
.active {
  border: 1px solid red;
}
<link href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap/5.2.1/css/bootstrap-grid.min.css" rel="stylesheet" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button type="button" onclick="setActive()">Mark Active </button>
<div class="logo-slider">
  <div class="logos row">
    <div class="col"><img class="logo" src="https://placehold.jp/3d4070/ffffff/150x150.png" /></div>
    <div class="col"><img class="logo" src="https://placehold.jp/3d4070/f4ffff/150x150.png" /></div>
    <div class="col"><img class="logo" src="https://placehold.jp/3d4070/ff6fff/150x150.png" /></div>
    <div class="col"><img class="logo" src="https://placehold.jp/3d4070/ffffff/150x150.png" /></div>
    <div class="col"><img class="logo" src="https://placehold.jp/3d4070/ffffff/150x150.png" /></div>
  </div>

</div>

2

Answers


  1. Chosen as BEST ANSWER

    Thanks for your help. Your comments were helpful. I found an alternate solution.

    Here's how I did it.

    $(".logo-slider .logos .logo")[0].classList.add("active");
    

    Got this idea after reading some of your comments. Thanks.


  2. You can use nth-child() css property to select specific element. Check snippet below..

    function setActive() {
        $(".logo-slider .logos .col:nth-child(2) .logo").addClass("active");
      }
    .active {
      border: 1px solid red;
    }
    <link href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap/5.2.1/css/bootstrap-grid.min.css" rel="stylesheet" />
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <button type="button" onclick="setActive()">Mark Active </button>
    <div class="logo-slider">
      <div class="logos row">
        <div class="col"><img class="logo" src="https://placehold.jp/3d4070/ffffff/150x150.png" /></div>
        <div class="col"><img class="logo" src="https://placehold.jp/3d4070/f4ffff/150x150.png" /></div>
        <div class="col"><img class="logo" src="https://placehold.jp/3d4070/ff6fff/150x150.png" /></div>
        <div class="col"><img class="logo" src="https://placehold.jp/3d4070/ffffff/150x150.png" /></div>
        <div class="col"><img class="logo" src="https://placehold.jp/3d4070/ffffff/150x150.png" /></div>
      </div>
    
    </div>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search