Adjust the class of a div element located close to its ancestor using JavaScript

I'm trying to change the class of the element #sidePanel from .compact to .expanded dynamically in this code snippet:

<div id="sidePanel" class="compact"></div>
<div id="topbar">
    <div id="buttonContainer">
        <div id="button"></div>
    </div>
</div>

I've hit a roadblock and can't figure out how to apply the class to the correct <div>; currently, I'm only able to add the class to the top bar. Here's what I have tried:

$(document).ready(function(){
    $("#button").mouseover(function(){
    $("this").parent().eq(2).addClass(".expanded").removeClass(".compact");
    });
});

I also attempted this method:

$(document).ready(function(){
    $("#button").mouseover(function(){
    $("#sidepanel").addClass(".expanded").removeClass(".compact");
    });
});

Answer №1

Your second example was almost there. When using $.addClass() and $.removeClass(), or mentioning classnames without selecting something, simply use the class name without the preceding .. It's important to note that JavaScript (and CSS) are case-sensitive, so $('#sidepanel') will not target #sidePanel - the cases must match.

    $("#button").mouseover(function() {
      $("#sidePanel").addClass("expanded").removeClass("compact");
    });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<style>.expanded {color: red;}</style>
<div id="sidePanel" class="compact">sidepanel</div>
<div id="topbar">
    <div id="buttonContainer">
        <div id="button">button</div>
    </div>
</div>

In your first example, $(this) is used to reference the current element in jQuery. If you enclose this in quotes, it becomes a string literal instead. To traverse up 2 levels with $.parent(), you should utilize $.parents() specifying the ID of the desired parent element, then apply $.prev() to select the previous element (#sidePanel). The correct approach to navigating the DOM would be as follows:

$("#button").mouseover(function() {
      $(this).parents('#topbar').prev().removeClass('compact').addClass('expanded');
    });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<style>.expanded {color: red;}</style>
<div id="sidePanel" class="compact">sidepanel</div>
<div id="topbar">
    <div id="buttonContainer">
        <div id="button">button</div>
    </div>
</div>

Answer №2

It seems the issue lies in using $("#sidepanel") instead of $("#sidePanel")

Check out the corrected code snippet below:

$(document).ready(function(){
    $("#button").on('mouseover', function(){
       $("#sidePanel").addClass("expanded").removeClass("compact");
    });
});
#topbar > div {
  width: 100px;
  height: 30px;
  background: #ccc;
  margin-top: 20px;
}

#sidePanel {
  width: 100%;
  height: 40px;
  background: #ccc;
}

#sidePanel.expanded {
  height: 100px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="sidePanel" class="compact"></div>
<div id="topbar">
    <div id="buttonContainer"></div>
    <div id="button"></div>
</div>

Answer №3

initially: the answer

$(document).ready(function()
{
    $("#button").mouseover(function()
    {
         // applying classes to specific elements
         $("#sidepanel").addClass("expanded").removeClass("compact");
    });
});

subsequently: the reason you nearly had it right at first

$(document).ready(function()
{
    $("#button").mouseover(function()
    {
        // using $(this) and correctly targeting classes
        $(this).parent().eq(2).addClass(".expanded").removeClass(".compact");
    });
});

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

Experiencing inaccuracies in Magento's item validation process when checking the quantity of items being added to the cart

Upon entering a text string in the quantity field of the "Add to Cart" input box, Magento does not display an error message but instead considers it as a quantity of "1". Is there a way to modify this behavior and have the validation system mark strings ...

Exploring the Concept of Dependency Injection in Angular 2

Below is a code snippet showcasing Angular 2/Typescript integration: @Component({ ... : ... providers: [MyService] }) export class MyComponent{ constructor(private _myService : MyService){ } someFunction(){ this._mySer ...

ways to change the font color style of a header element using css

Below is the HTML code that I need to work with: <h5 class="post-title">Welcome To The Site</h5> I am attempting to change the font color to red using this CSS: .post-title{ color:red ! important; } However, my attempt was unsuccessful ...

Create a custom overlay for an image that is centered horizontally and does not have a fixed width

I'm working with this HTML setup: <div class="container"> <img class="image" /> <div class="overlay"> <div class="insides">more content here</div> </div> &l ...

Sub-menu disappears upon resizing the screen

Currently, I am working on creating a unique responsive navigation system that transforms into a 100% width pulldown menu for mobile devices. To achieve this functionality, I have implemented some JavaScript code that hides any open sub-menu items when the ...

Creating separate files for establishing DB connection and writing Node.js queries is a recommended practice for organization

Having an issue with connecting dbconnection.js and demo_api_select.js. When trying to declare a variable in demo_api_select.js, I am encountering errors like this: Error Notification Please assist me in resolving this problem. dbconnection.js: var ...

Easily validate your email with this straightforward form. Completely puzzled

Today's challenge is tackling the email validation form issue. While searching for a solution, I stumbled upon an interesting code snippet: http://jsfiddle.net/jquery4u/5rPmV/ dyingOverHere(); The code seems to work flawlessly in the demo provided. ...

Tips on arranging jQuery deferred objects in order?

I am facing an issue where I need to delay every Ajax call until the previous function (hashcode.Sign()) has completed. Unfortunately, my current code does not wait for hashcode.Sign() to finish, causing problems as this function creates a new session that ...

Creating element modules in EJS

After building experience with React, I am now faced with the task of using ejs in my current project. Specifically, I need to return multiple radio elements. My attempt at achieving this was through the following code: <% const renderRadios = (value, ...

Embed a hyperlink within an informational passage

I have a search box with Ajax functionality like this; And I want to customize the NotfindText message to display as: "No results found, but you can try advanced search from here" However, I am struggling to add the link. I do not have much knowledge abo ...

Creating a type definition for the createSelector function based on the useQuery result

Struggling to find the correct typings for the createSelector res parameter from redux-js, especially in TypeScript where there are no examples or explanations available. The only guidance is provided in JS. const selectFacts = React.useMemo(() => { ...

When running the command `npx create-react-app client`, an error is thrown stating "Reading properties of undefined is not possible (reading 'isServer')."

Installing packages. Please wait while the necessary packages are being installed. Currently installing react, react-dom, and react-scripts with cra-template... Encountered an error: Unable to read properties of undefined (reading 'isSer ...

Step-by-step guide on displaying SVG text on a DOM element using Angular 8

I have a FusionChart graph that I need to extract the image from and display it on the same HTML page when the user clicks on the "Get SVG String" button. I am able to retrieve the SVG text using this.chart.getSVGString() method, but I'm unsure of ho ...

Assign a predetermined value to a dropdown list within a FormGroup

I have received 2 sets of data from my API: { "content": [{ "id": 1, "roleName": "admin", }, { "id": 2, "roleName": "user", }, { "id": 3, "roleName": "other", } ], "last": true, "totalEleme ...

Adapting iFrame height to accommodate fluctuating content height in real time (details included)

I have an embedded iframe that contains a form with jQuery validation. When errors occur, the content height of the iframe increases dynamically. Below is the script I use to adjust the height of my iframe based on its content: function doIframe(){ o = d ...

Unable to execute JS script to navigate back to prior page with webdriver

Here is my code snippet: JavascriptExecutor jse = (JavascriptExecutor)driver; jse.executeScript("window.history.go(-1);"); The code above isn't working. I've tried casting the webdriver instance but it doesn't work every time. I prefer not ...

What is the best way to ensure an image fits perfectly within a div container

I'm attempting to design a straightforward card layout where the image spans the entire width of the container div. My vision is for it to resemble something like the example in the linked image below. https://i.sstatic.net/X5oJD.png I experiment ...

The Firebase signInWithPopup functionality suddenly shuts down in a Next.js project

Incorporating the signInWithPopup function for signing in has been successful during the development stage on my local server. const firebaseAuth = getAuth(app); const provider = new GoogleAuthProvider(); const [{ user, cartShow, cartItems }, dispatc ...

Creating HTML Textarea to Show Text with Newline and Spacing

I would like to have a pre-populated text area on my webpage that says: Hi, enter some text here And press submit:) This is just an example, I realize it may seem silly. However, when I put this directly into the HTML code, it shows up like this: Hi ...

Modifying the input field's name attribute while utilizing multiple datasets in typeahead.js

I am currently utilizing typeahead.js with multiple datasets, following the guidance provided here. I have chosen not to employ Bloodhound in my implementation, resulting in some differences in my code structure, outlined below: $('#search .typeahead ...