Applying and deleting CSS classes to the nth ancestor element

Is there a way to dynamically add and remove CSS classes to the parent of a specific element on a web page using a link button? Here is the code snippet:

<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>

I am attempting to change the class "prod-box shadow" to "prod-box shadow-blue". The jQuery code I tried was:

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

Answer №1

If you're looking for a way to target the closest element, then you should use .closest().

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

To toggle between different classes, you can utilize toggleClass().

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

Note that the .parent() method only searches for the direct parent element and applies the given selector to that specific parent element.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

I found that when using a variable with a dynamic value in a function, it is preventing me from successfully submitting a form through ajax

Many forms with different classes are present on a single page, each having two buttons to submit the parent form. The form submission occurs upon clicking either #avote_down or #avote_up. The script captures the class of the parent form of the clicked bu ...

Refreshing the session cookie during an ajax request in CodeIgniter

Here is the ajax call I am using: remote: { url:"http://localhost/my_site/index_page/validate_name", type: "post" } Within the validate_name function, I am setting the session cookie in this way: $username = "t ...

Discrepancies in media screen queries displaying on inspection tools compared to actual device

I've done some research online but I'm still struggling with this issue. Despite creating media screen queries and setting the viewport for iPhone 7 plus, the website does not display correctly on my device. When I inspect it using Chrome, every ...

Ways to set Material UI tabs as active exclusively for particular URLs

Looking for a solution to address a conflict arising from the active tab indicator being located on the right tab. Within my navbar, I have tabs leading to three different routes, two of which are quite similar. <Tabs indicatorColor="primary" ...

Locate the final descendant element within the JSON document

My JSON file is structured as follows: "FAMILY": { "1": { "ANNA": { "name": "ANNA X", "alive": true, "children": { "MAX": { "name": "MAX X", ...

Styling JQuery UI dialog with an external CSS file

I found a helpful resource at http://jqueryui.com/demos/dialog/ $('#add_remarks').click(function(){ $( "#remark-form" ).dialog( "open" ); }); $( "#remark-form" ).dialog({ autoOpen: false, modal: true, buttons: { 'Add ...

CSS problem: HTML element moving to the right upon clicking

Currently, I am utilizing a jQuery popup to present additional information to users. The setup involves having a link on the page that triggers the popup to appear from the top. The popup script being used is sourced from CodePen. However, an issue arises ...

Pace.js doesn't bother waiting for iframes to completely load before moving on

On my website, I am using pace.js but encountering issues with pages containing iframes. Is there a method to ensure that pace.js considers the content loading within those iframes? I attempted to configure paceOptions to wait for the iframe selector to l ...

Pause the loading of information for a brief 2-second interval using jQuery's ajax feature

I want to enhance the user experience by loading search results using jQuery ajax within a div container. To achieve this, I am looking to introduce a 2-second delay before displaying the results or show them only after the user has entered at least three ...

I am having an issue with my DIV not functioning correctly in conjunction with my JS animation. What modifications should I make to

I have a simple JS animation script that fetches data from the <div class="quiz"> Some content </div> for animation. When I include this script in my HTML, the animation and other functions such as previous and next work properly. See ...

Displaying a JQuery notification when hovering over a link

I am having trouble getting an alert to pop up when I hover over a hyperlink using JQuery and Javascript. The hyperlink is inside an anchor within the main section of the HTML. Any assistance would be much appreciated. Here is my current code snippet: &l ...

The function cannot be applied to the size of the map within the action payload

Is there a way to replace the for loop with the map method? The data structure for book.pages is in the format [{},{},{}] I tried using the size method and included this line console.log("book.pages.map.size();--->", book.pages.map.si ...

What kind of GWT component features both a Button and text?

I am looking to develop a customized GWT widget that consists of a rectangular div element resembling a button, accompanied by text positioned adjacent to it. My goal is to enable the selection of this widget so that clicking on either the div/button or th ...

Executing action in PHP script simultaneously with Ajax

My JavaScript skills are a bit rusty, and I need help adding a "delete" feature to some code that displays rows of data. The code includes PHP, jQuery, and other JS elements. Here's the snippet: <?php require_once '../../app/Mage.php'; M ...

"Strategies for using Selenium in Python to simulate clicks without relying on class, id, or name attributes

I am currently attempting to locate the "X" button and click on it, but I am struggling to find a way to do so. Below is the HTML code for the element: <div style="cursor: pointer; float:right; border-radius: 3px; background-color: red; font-size: ...

Is it possible to move the login button to the right side of the screen?

I'm attempting to move the Login menu all the way to the right on the navigation bar. Currently, all the menu items are aligned to the left and I need to align the Login menu to the right. However, I'm unsure of where to begin. The navigation me ...

Text overlay on image sliders inside div containers

Is there a way to display div elements on top of an image slider, rather than behind it? I've tried using z-index and position: absolute with no success. Here is an example: HTML: <div id="header"> <img src="assets/images/header1.png" / ...

Learn how to implement Bootstrap 4's select styling to customize dropdown links, such as using it for a tags

My goal is to apply Bootstrap 4 form styling, like form-control and custom-select, to actual links (dropdown a tag). For example: <select class="custom-select" onchange="location = this.value;"> <option selected>Cho ...

Center content within a div using the middle alignment

Here's a question that goes beyond your typical "vertical align center" query. What I want to accomplish is to take a div with an unspecified height and position it at a specific percentage down the page, let's say 33%. I have managed to get this ...

Display additional javascript code for expanding a marquee

Currently, I am working on a stock ticker project using JavaScript. It's progressing well, and now I am focusing on adding a "show more" button to style the ticker. The button should be placed outside of the marquee. When clicked, it will expand the m ...