How to add class to only one of multiple same elements
You were on the right track by using $(this)
but then reverted back to using $('.caret')
. Do this:
$(".caret").click(function () {
$(this).toggleClass('opened');
});
Askers request to close all other .caret
classes:
$(".caret").click(function () {
$(".caret").removeClass('opened');
$(this).addClass('opened');
});
Your HTML is invalid so it is going to produce wrong HTML Markup in the browser. Not knowing how you actually want it to look, I can not offer a solution on fixing it. Once you get it fixed, The basic code should be
$('.caret').on('click', function () {
$('.caret.opened') // all the open carets
.not(this) // removed the one that was clicked
.removeClass('opened'); // remove the class
$(this)
.toggleClass('opened'); // toggle the one that was clicked
//.addClass('opened'); // if you want it always open
});
if one always has to be opened
$('.caret').on('click', function () {
$('.caret.opened') // all the open carets
.removeClass('opened'); // remove the class
$(this)
.addClass('opened'); // set clicked to open
});