0

I want to add and remove css class with a link button on my web page to nth(ProdBox) parent: Code below

<div class="prod-box shadow">
    <div class="prod-details">                    
    </div>
</div>
<div class="prod-compare">
    <div class="compare">
        <a href="javascript:void();" class="add-to-compare" data-id="123">Add to Compare</a>
    </div>

</div>
</div>

I want to replace the top parent class "prod-box shadow" with "prod-box shadow-blue". I tried below jquery 1.9.1 code, but not working:

$(this).parent('div .prod-box').removeClass('shadow');
$(this).parent('div .prod-box').addClass('shadow-blue');

1 Answer 1

1

.closest() is what you are looking for

$(this).closest('.prod-box').removeClass('shadow').addClass('shadow-blue');

use toggleClasss() to switch between the classes

$(this).closest('.prod-box').toggleClass('shadow shadow-blue');

The .parent() method only search for the direct parent element and the applies the given selector to that parent element

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks Arun, Little more favour required from you. Please see this fiddle jsfiddle.net/DBfKz/17 here parent.remove not wokring in jquery 1.9.1 while working in 1.4.2. You can try to add product and click on x button to remove them.
@user1610100 .live() is removed in jQuery 1.9, use .on() instead like $(document).on("click", ".box a", function () { see jsfiddle.net/arunpjohny/mSF67/1

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.