JQuery does not have the capability to target neighboring elements

How can I get a user to click on a tag that is inside an li element (div ul li a)? By default, the first a tag has a class of 'on'. When the tag is clicked, the code should add the class 'on' to the clicked element and remove it from all other siblings. However, the removal of the class from siblings is not working as expected.

var menu01_list = $(".profile_menu01 ul li > a");

menu01_list.click(function(){
  $(this).siblings().removeClass('on');
  $(this).addClass('on');
});

Here is the HTML code:

<div class="profile_menu01">
    <ul>
        <li><a class="btn_my_pick on" href="#">My Pick</a></li>
        <li><a class="btn_my_pickpot" href="#">3<span class="alert_num"></span>My Picpot</a></li>
        <li><a class="btn_my_review" href="#">My ReView</a></li>
        <li><a class="btn_my_photos" href="#">My Photos</a></li>
    </ul>
</div>

Answer №1

When you are examining the siblings of the <a> element within the context of the <li>, there actually are no direct siblings at that level. In order to find siblings, you need to traverse one level up to the <li> and then back down again:

menu01_list.click(function(){
   $(this).parent().siblings().children().removeClass('on');
   $(this).addClass('on');
});

An alternative approach is to run the function on the li itself:

var menu01_list = $(".profile_menu01 ul li");

menu01_list.click(function(){
   $(this).siblings().children().removeClass('on');
   $(this).children().addClass('on');
});

Answer №2

Based on the code you provided (.profile_menu01 ul li > a), it seems that there is no immediate sibling for the a tag. You can utilize the code snippets below to remove the on class.

$(this).closest("ul").find("a.on").removeClass("on")

For example:

 var menu01_list = $(".profile_menu01 ul li > a");

 menu01_list.click(function() {
   $(this).closest("ul").find("a.on").removeClass('on');
   $(this).addClass('on');
 });
.on{
  background:Yellow;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="profile_menu01">
  <ul>
    <li><a class="btn_my_pick on" href="#">My Pick</a></li>
    <li><a class="btn_my_pickpot on" href="#">3<span class="alert_num"></span>My Picpot</a></li>
    <li><a class="btn_my_review on" href="#">My ReView</a></li>
    <li><a class="btn_my_photos on" href="#">My Photos</a></li>
  </ul>
</div>

Answer №3

There is a minor error in the script below:

var menu01_list = $(".profile_menu01 ul li > a");

    menu01_list.click(function(){
       $(this).siblings().removeClass('on');
       $(this).addClass('on');
    });

In the code above, you are attempting to remove classes from the <a> anchor tag which is not a sibling element as these anchor tags are separated by the parent element <li>.

To resolve this issue, try using the following script:

var menu01_list = $(".profile_menu01 ul li > a");

    menu01_list.click(function(){
       $(this).parent().siblings().children('a').removeClass('on');
       $(this).addClass('on');
    });

Answer №4

let menuItems = $(".profile_menu01 ul li > a");

    menuItems.click(function(){
       $(this).parent().siblings().children('a').removeClass('active');
       $(this).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

What is the best way to seamlessly transition from responsive design to mobile design?

While developing a single-page app, I encountered an issue with the layout when the screen width reaches a specific point. On narrow screens, I prefer to utilize the full width, but for wider screens, I want to limit the width for better readability. The l ...

Creating an arrow line with CSS styling can be achieved easily

In order to create a horizontal line with a breakdown in the middle that displays an arrow, I want to use only HTML and CSS without relying on bitmap images. If needed, Font Awesome can be used to achieve the desired result. It's important for me to h ...

conceal the android keyboard when focusing

Encountering an issue with my web application. Seeking a method to conceal the android keyboard when a text input is focused without disrupting the input focus. The focus on page load is working well as the field is focused and the keyboard is not displ ...

Designate the preferred location for requesting the desktop site

Is there a way to specify the location of the 'Request desktop site' option? Here is the code I am currently using: var detector = new MobileDetect(window.navigator.userAgent); if(detector.mobile() != null || detector.phone() != null || det ...

Xpath attribute of Selenium element

I am having trouble extracting the attribute from the "data-nice-url" element in my HTML code: <div class="car-thumb-item clickable vehicle " data-include_settings="true" data-nice_url="/privatleasing/Citro%c3%abn-Berlingo/eHDi-90-Seduction-E6G" data-i ...

How to Properly Wrap Sub-Menu Elements in WordPress with Div Tags

I am currently working on styling my WordPress sub menu list items using HTML. I have written the HTML code that I want to use, but I am not sure how to incorporate it into the wp_nav_menu() function. Can you assist me with this? <ul class="menu"> ...

Retrieve the current value of an item by scrolling through it

I have a functioning sample of a scrollable with item numbers 1 - 24. I am trying to retrieve the value of the current item, but my attempts to use alert have failed. How can this be achieved? Here is my code: UPDATE QUESTION: I managed to obtain the inde ...

Exploring the Spotify API with jQuery/ajax to fetch details about songs, artists, and albums

I've been researching and have come across some information that is somewhat similar, but I'm still struggling to completely understand how this process works. My goal is to make a request to the Spotify API using jQuery to search for an artist ...

Looking to extract the hidden value from an HTML input field using Selenium

Unable to retrieve the value of a hidden element in HTML, even though it is displaying. Seeking assistance in accessing the value despite the type being hidden. <input type="HIDDEN" label_value="Sub Reference" title="Sub Reference" id="ACC_NO" dbt="BK_ ...

The issue of Markdown not being recognized inside nested divs

As I develop a Bootstrap-themed website with Jekyll, I've encountered an issue when formatting content in markdown. My goal is to organize my posts using Bootstrap grids like this: <div class="row"> <div class="col col-md-6" markdown="1"&g ...

What is the maximum number of files that FileUploader can accept when multi-select is enabled?

I encountered the following issue: A first chance exception of type 'System.Web.HttpException' occurred in System.Web.dll Additional information: Maximum request length exceeded. while attempting to upload 250 JPEG files, each around 98 KB in ...

Launching a webpage programmatically

I have developed a Windows C# script that automatically generates HTML files and constructs a webpage with links to those files. The variable reportName holds the path and name of the final webpage. This script is triggered from a webpage, and once the re ...

Accessing the Bootstrap tab form from an external source

I currently have Bootstrap tabs on a page and they are functioning correctly. However, I am looking to open these tabs from an external page. Is this feasible? <div role="tabpanel"> <ul class="nav nav-tabs" role="tablist"> ...

Transition effect does not work properly when using ng-hide

I am currently working on an application that requires a button to be clicked in order to hide or show a specific element. To achieve this functionality, I am using ng-hide in AngularJS, but I am facing an issue where the transition is not working as expe ...

"Customize your Vuetify v-card with uniquely styled rounded corners on only

I am seeking to create a unique v-card design where only two corners are rounded. Despite my attempts, the card ended up rotated by 90° and didn't achieve the desired outcome. DESIGN ATTEMPT: <div class="text-center rotate-ninety ml-n6" ...

Guide on extracting the date selected from a Bootstrap datepicker and displaying it in a separate div

I'm currently attempting to extract the date from a button and display it in another div. Initially, I tried using the input tag method but faced some issues. Therefore, I switched to employing the button option with an icon. My main challenge now is ...

Adjust transparency according to the information extracted from the AnalyserNode

Currently, I am exploring ways to animate text opacity based on the volume of an audio file. While browsing online, I came across this specific codepen example, which showcases a similar concept. However, as I am relatively new to JavaScript, I find it ch ...

The method of displaying milliseconds in a JavaScript countdown timer

I have a piece of javascript code that is responsible for showing a countdown timer starting from 5 minutes. Here is the code snippet: var mins var secs; function startCountdown() { mins = 1 * m("05"); // set the minutes here secs = 0 + s(":00") ...

AngularJS function orderBy reverses the array instead of sorting it

I encountered an issue where, after clicking the 'order button', the table does not order as expected. Instead, it reverses all the td elements. For example, 'A', 'C', 'B' becomes 'B', 'C', "A". I ...

How can you display two images by hovering your mouse over them?

I am attempting to create a header that resembles the one found at . I am curious about how they were able to make it flash when hovering over the home button. I understand that two images are required for this effect, but I am unsure of the specific func ...