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 >
<div >
<div ><img src="https://placehold.jp/3d4070/ffffff/150x150.png" /></div>
<div ><img src="https://placehold.jp/3d4070/f4ffff/150x150.png" /></div>
<div ><img src="https://placehold.jp/3d4070/ff6fff/150x150.png" /></div>
<div ><img src="https://placehold.jp/3d4070/ffffff/150x150.png" /></div>
<div ><img src="https://placehold.jp/3d4070/ffffff/150x150.png" /></div>
</div>
</div>
CodePudding user response:
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 >
<div >
<div ><img src="https://placehold.jp/3d4070/ffffff/150x150.png" /></div>
<div ><img src="https://placehold.jp/3d4070/f4ffff/150x150.png" /></div>
<div ><img src="https://placehold.jp/3d4070/ff6fff/150x150.png" /></div>
<div ><img src="https://placehold.jp/3d4070/ffffff/150x150.png" /></div>
<div ><img src="https://placehold.jp/3d4070/ffffff/150x150.png" /></div>
</div>
</div>
CodePudding user response:
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.