Coder Coder - 2 months ago 6
Javascript Question

Add class to previous element using jquery

I am adding classes namely hide_some_features,show_some_features in each loop. Now i want to add class to feature_suffix having next only hide_some_features class. I tried with

$(this).closest('.feature_suffix').addClass('test-class');
which is not working.

$('.variations_form input:radio[name=attribute_pa_1]').each(function() {
if (jQuery.inArray($(this).attr('data-feature-value'), disabledFetaureValue) < 0) {
$(this).closest('.cc-selector').addClass('hide_some_features');
$(this).closest('.feature_suffix').addClass('test-class');
} else {
$(this).closest('.cc-selector').addClass('show_some_features');
}
})


;
enter image description here

I want to add class to highlighted place

Answer

.closest() wont work here because the target element is not an ancestor of the element that fires the event. Use the below:

$(this).closest('.cc-selector').prev('.feature_suffix').addClass('test-class');

enter image description here

Comments