Click on an element using jQuery to apply a specific class to all other similar

I am looking to dynamically add a class to a DIV after clicking on an A element with the same class. Here is an example:

<ul>
<li><a href="#1" class="test1">1</a></li>
<li><a href="#2" class="test2">2</a></li>
<li><a href="#3" class="test3">3</a></li>
</ul>
<div class="test">
<div class="test1">test1</div>
<div class="test2">test2</div>
<div class="test3">test3</div>
</div>

If I click on a.test1, I want to add the class ACTIVE to both the a and div elements with the class test1. I have managed to achieve this for the A element using jQuery, but I'm not sure how to handle it for the DIV element.

jQuery(document).ready(function() {
    jQuery('ul li').click(function() {
        jQuery("li.active").removeClass("active");
        jQuery(this).addClass('active');
    });
})

Any suggestions or solutions are greatly appreciated! Thank you!

Answer №1

If you want to retrieve the corresponding div element based on the position of the clicked li, you can achieve it by following this approach:

$(document).ready(function() {
  $('ul li').click(function() {
    var index = $(this).index();
    $(this).addClass('active').siblings().removeClass('active');
    $('.container div').eq(index).addClass('active').siblings().removeClass('active');
  });
})
.active {
  font-weight: bold;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul>
  <li><a href="#1" class="item1">1</a></li>
  <li><a href="#2" class="item2">2</a></li>
  <li><a href="#3" class="item3">3</a></li>
</ul>
<div class="container">
  <div class="item1">Item 1</div>
  <div class="item2">Item 2</div>
  <div class="item3">Item 3</div>
</div>

Answer №2

Hopefully the code below will function as expected:

jQuery(document).ready(function() {
    jQuery('ul li').click(function() {
        jQuery("li.active").removeClass("active");
        var divClass = jQuery(this).attr("class"); 
        jQuery(this).addClass('active');

        jQuery("div.active").removeClass('active');
        jQuery("div."+divClass).addClass('active');
    });
})

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 currently have an array of strings and wish to print only the lines that include a specific substring

Here i want to showcase lines that contain the following strings: Object.< anonymous > These are multiple lines: Discover those lines that have the substring Object . < anonymous > Error: ER_ACCESS_DENIED_ERROR: Access denied for user ' ...

Utilizing Javascript in Spotfire for enhanced functionality

Currently, I have a dropdown menu with two options ("START" & "END"). Depending on the selected value from this dropdown, I want to display a specific DIV element. I attempted to use the code below, but unfortunately, it is not functioning as expected ...

Enhance your slideshow with a stylish fade effect

I found this slideshow on codepen and decided to customize it to make it my own. While everything is working well, I wanted to incorporate a fade effect into the transition between slides. I'm unsure whether I should add something to the CSS file or m ...

Tips for implementing a jQuery mouseleave function for multiple div elements sharing the same id

I am facing an issue with my website where multiple divs share the same id. I need to implement a mouseleave function for all of these divs that have this specific id. Within my $(document).ready function, I currently have the following code... $('#m ...

Incorporating a new function into a TypeScript (JavaScript) class method

Is it possible to add a method to a method within a class? class MyClass { public foo(text: string): string { return text + ' FOO!' } // Looking for a way to dynamically add the method `bar` to `foo`. } const obj = new MyCl ...

During the process of converting documents to HTML, any graphics or shapes may not be accurately translated into HTML format

I am looking for a way to display a doc file in a dialog box on a browser. To achieve this, I converted the doc file into an html file successfully. However, I encountered an issue when the doc file contained graphics or shapes - these elements were not co ...

Searching for TypeScript type definitions for the @Angular libraries within Angular 2

After updating my application to Angular2 v2.0.0-rc.1, I am encountering TypeScript compile errors and warnings when webpack bundles my application. These messages appear for any @angular packages referenced in my TypeScript source files: ERROR in ./src/a ...

Monitor when a button in a grapesjs modal is clicked

When using the Grapesjs Editor, I needed a modal with a form inside it. Upon clicking the submit button, I wanted to trigger a Function that would make an ajax call. To achieve this, I attempted to create a custom component by extending it from the defaul ...

What is the best way to consolidate all app dependencies into a single package?

Recently, I came across Cory House's ingenious solution for package management in Node.js during his informative presentation. In their project portfolio, House's team maintains a package called Fusion, which serves as a central repository for a ...

Developing a unified input element containing numerous fields

After @grateful answered this question, I wanted to elaborate in case it could benefit others... In my project, there's a page called rsetup.php which has some PHP code to access a MySQL database for filling the HTML content of the page. This HTML ge ...

Site performance stalls when a trailing slash is present in the URL while using Express routing

Whenever I visit a page on my development site with a URL like localhost:8000/news, everything loads perfectly fine. However, if I add a trailing slash to the URL, such as localhost:8000/news/, the entire site freezes. It seems to be trying to load partial ...

What could be causing my React Router component to display incorrect styling?

While working with react-router, I encountered an issue where the text from the routed page started appearing in the navbar. Even though I separated it as its own component and it functions correctly, this specific problem persists. As a newcomer to React, ...

Position two div elements and an hr tag to create a step progress bar

Check out my progress bar design https://i.sstatic.net/u9SRM.png How can I center the 'created' and 'assigned' divs below the circle while ensuring the 'hr' line touches the circle, and it is responsive across different scre ...

Can the useNavigation hook be used to navigate to a class component in React?

How can I use the useNavigation hook to navigate to a class component? Here is my class: export default class AzureLogin extends React.Component I want to navigate to AzureLogin from Screen1. What is the correct way to achieve this? import { useNavigati ...

I am experimenting with showcasing a series of Bootstrap div elements, each containing a dynamic carousel of images sourced from a database along with additional information

My image display is working fine, but the other divs are appearing within the first div and the additional information like title and description are not showing. I'm aiming to have six rows, each with two columns, displaying a carousel of images and ...

The feature of interpolation within attributes has been eliminated. Please use either v-bind or the colon shorthand in its place

I am struggling to grasp how I can pass a value to Vue using HTML. I keep encountering this error message: Interpolation inside attributes has been removed. Use v-bind or the colon shorthand instead. Edit: I am trying to pass the value "country" to the Vu ...

Maintaining the consistent structure of build directories within a Docker container is crucial, especially when compiling TypeScript code that excludes the test

Our application is built using TypeScript and the source code resides in the /src directory. We have tests located in the /tests directory. When we compile the code locally using TSC, the compiled files are deposited into /dist/src and /dist/test respectiv ...

Removing Specific Items from a List in React: A Step-by-Step Guide

I have developed a basic ToDo List App. The functionality to display tasks from the input form is working correctly, but I am facing issues with deleting tasks when the Delete button is clicked. export class TaskList extends Component { constructor(pr ...

Embedding images using a blob or base64 format does not function properly on iOS devices

I'm facing an issue with setting the src of an img tag to display an image. The code snippet below works fine on android, mac, and windows, but it is not functioning correctly on iOS: let base64Image = pageModel.image; this.$currentPageImage.src = `da ...

Is there a way to modify an element in an array in AngularJS without using splice?

I encountered a situation similar to the one described in this post here, where I not only want to retrieve an element but also change its name value. I came across a method that involves using splice: dataList.splice(index, 1); dataList.splice(index, 0, ...