Children can easily access multiple items within a list by using the ul tag

I am struggling with changing the class of ul inside the ul.navigator. I want to change it only when I click on a particular li, but my current approach doesn't seem to be working. Can anyone provide some guidance or assistance?

$('.navigator').children('li ul').each(function() {
  if ($(this).hasClass('opened')) {
    $(this).addClass('closed');
    $(this).removeClass('opened');
  } else {
    $(this).addClass('opened');
    $(this).removeClass('closed');
  }
});
.opened {
  color: green
}
.closed {
  color: red
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul class="navigator">
  <li class="elem1">
    <span>Element 1</span>
    <ul class="opened">
      <li>Item 1</li>
      <li>Item 2</li>
    </ul>
  </li>
  <li class="elem2">
    <span>Element 2 </span>
  </li>
  <li class="elem3">
    <span>Element 3 </span>
  </li>
</ul>

Answer №1

To achieve the desired result, it is recommended to utilize .find() instead of .children()

When comparing .find() and .children(), note that the latter specifically navigates one level deep into the DOM tree.

$('.navigator').find('li ul')

OR, leverage the Descendant selector

$('.navigator li ul')

$('.navigator').find('li ul').click(function() {
  if ($(this).hasClass('opened')) {
    $(this).addClass('closed');
    $(this).removeClass('opened');
  } else {
    $(this).addClass('opened');
    $(this).removeClass('closed');
  }
});
.opened {
  color: green
}
.closed {
  color: red
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul class="navigator">
  <li class="elem1">
    <span>Element 1</span>
    <ul class="opened">
      <li>Item 1</li>
      <li>Item 2</li>
    </ul>
  </li>
  <li class="elem2">
    <span>Element 2 </span>
  </li>
  <li class="elem3">
    <span>Element 3 </span>
  </li>
</ul>

Answer №2

Here's a suggestion on how to approach it:

$('.navigator > li').on('click', function() {
  $('.navigator').children('li ul').each(function() {
    if ($(this).hasClass('opened')) {
      $(this).addClass('closed');
      $(this).removeClass('opened');
    } else {
      $(this).addClass('opened');
      $(this).removeClass('closed');
    }
  });
});

This method ensures that when an li directly under .navigator is clicked, the code will execute as intended.

Answer №3

implementing toggle Method

$('.navigator li').click(function(){
             $(this).children('ul').toggleClass('closed');          
        });

View the Demo Here

Code Snippet

$('.navigator li').click(function(){
             $(this).children('ul').toggleClass('closed');          
        });
.closed
{
  display:none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
   <ul class="navigator">
      <li class="elem1">
        <span>Element 1</span>
        <ul class="opened">
          <li>Item 1</li>
          <li>Item 2</li>
        </ul>
      </li>
      <li class="elem2">
        <span>Element 2 </span>
      </li>
      <li class="elem3">
        <span>Element 3 </span>
      </li>
    </ul>

Answer №4

Enhance your code by utilizing toggleClass

   $('.navigator li ul').click(function(){
         $(this).toggleClass('closed');          
    });

Alternatively

for a different approach to resolving the issue, consider the following:

  1. use childern apply with same line $('.navigator li ul').
  2. Apply removeclass before addClass.
  3. And Don't forget to add jquery library

Code Snippet

$('.navigator li ul').click(function(){
        if($(this).hasClass('opened')){
            $(this).removeClass('opened');
            $(this).addClass('closed');
          
        } else {
            $(this).addClass('opened');
            $(this).removeClass('closed');
        }
    });
.opened{color:green}
.closed{color:red}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul class="navigator">
  <li class="elem1">
    <span>Element 1</span>
    <ul class="opened">
      <li>Item 1</li>
      <li>Item 2</li>
    </ul>
  </li>
  <li class="elem2">
    <span>Element 2 </span>
  </li>
  <li class="elem3">
    <span>Element 3 </span>
  </li>
</ul>

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

Loading logos dynamically using Jquery upon selection of an option

In the form I created, there is a dropdown logo selection at the bottom. The options in the dropdown are populated from folders in the root directory using the following code: $dirs = glob('*', GLOB_ONLYDIR); Each of these directories contain ...

A regular expression in JavaScript for matching unpredictable numbers without any specific words preceding them

For instance, I am looking to extract the numbers that do not have 'the', 'abc', or 'he' before them; the89 (no match) thisis90 (match 90) iknow89999 (match 89999) getthe984754 (no match) abc58934(no match ...

Using dropzone.js on multiple files in a single webpage

Is it feasible to incorporate multiple dropzone elements on one webpage instead of having numerous file uploads on a single dropzone element? It appears that dropzone fails to trigger after the selection dialog box when there are several elements, each wi ...

Error: The function window.intlTelInput is not recognized within the ReactJS framework

I am currently learning ReactJS and encountering an issue when using jQuery with React JS for intlTelInput. I have installed npm jQuery and imported all the necessary code. Additionally, I have included all the required CSS and jQuery links in my index.htm ...

integrating a ui-bootstrap modal in a sidebar using angularjs

I recently utilized the modal example from https://angular-ui.github.io/bootstrap/ and everything worked perfectly. By using the code snippet below, I was able to successfully open the modal as shown in the example: $scope.open = function (size) { v ...

The element type provided is not valid: it is expected to be a string (for built-in components) or a class/function (for composite components) but instead it is undefined. This error

I am encountering an error of Element type is invalid: expected a string (for built-in components) or a class/function (for composite components). It seems like I may have forgotten to export my component from the file it was defined in, or there could be ...

Designing a button component with text

Exploring My Demo Page, I am attempting to design a button that will serve as a closure mechanism for modals. The code snippet I experimented with is as follows: x=document.createElement('button'); x.className='superclose'; Referencin ...

Using AngularJS to encapsulate an externally loaded asynchronous library as a service

Is there a way to wrap a 3rd party library that loads asynchronously into an Angular service? What is the best practice for incorporating such libraries as services in Angular? Currently, I am approaching it like this: angular.module('myAPIServices ...

How to retrieve values from HTML class names using Javascript for loops but encountering issues

foreach($products as $row){ <input type="hidden" class="prodId" name="id" value="<?php echo $row['id']; ?>"> <input type="hidden" class="prodUnique" name="unique" value="<?php echo $unique; ?>"> <button id="added" ...

Retrieve the information from a website and display it on the current webpage using an ajax request

Is there a way to insert parsed HTML content into my webpage using just a link from another page? I'm attempting to use an AJAX call, but I keep receiving an error. Below is the code I've written, and the browser doesn't seem to be the issue ...

Error: Unable to parse JSON field value due to an unexpected OBJECT_START

Currently in my coding project, I am utilizing node and mongoose to update a Watson rank and access the database. My goal is to insert multiple documents into the collection. While I can successfully add a single document, I encounter issues when creating ...

Dealing with errors such as "Failed to load chunk" can be resolved by implementing lazy-loading and code-splitting techniques

Our team is currently working on a Vue.js application using Vue CLI 3, Vue Router, and Webpack. The routes are lazy-loaded and the chunk file names include a hash for cache busting purposes. So far, everything has been running smoothly. However, we encoun ...

Discovering the moment when the next() function has reached the last item and transitioning back to the first item

Currently, I am utilizing the next() function to showcase a sequence of elements. However, once I reach the last element, my goal is to loop back to the first element in the series. Any suggestions on how to achieve this? Below is the code snippet I am wo ...

The versatility of reusable Backbone components

As I search for the best way to ensure the reusability of Backbone views, I have come across various solutions but am unsure which one would best meet my needs. My goal is to create multiple widgets populated with real-time data and I require a base compon ...

Tips for altering the appearance of a dropped item using JQueryUI sortable

I have a straightforward website where I need to implement the ability to drag and drop styled DIV elements between two containers. Utilizing JQueryUI's sortable function, this behavior was successfully achieved with the following code: $("#active-co ...

AngularJS: Utilizing nested ng-repeats for dynamic data rendering

Currently, I am utilizing the ng-repeat directive in conjunction with the ng-repeat-start/ng-repeat-end options. Within the main loop, there is an additional inner ng-repeat. However, the problem lies in the fact that the outer ng-repeat-start declaration ...

Creating an editable list item with jQuery: A step-by-step guide

I am trying to create a user-friendly interface where users can view and edit their information in a listview. The data will be retrieved from a database and displayed in the listview. My goal is to make the listview editable, so when a user clicks on it ...

ReactJS - Travel Booking Platform with Advanced Date and Price Filtering

Currently, I am in the process of developing a project — a website similar to AirBnB or Booking.com for booking rooms. The backend is built on Java Spring, while the frontend uses ReactJs. Although most of the code runs smoothly, I'm encountering s ...

"Calculating the total value of an array based on its individual elements

My API response includes committers to a git project, but some members are repeated because they share the same name with different email addresses. Example response: [ {"id": "122334", "name": "bob", "commits":10, "email": "<a href="/cdn-cgi/l/emai ...

I am interested in placing focus on a specific grid column within Kendo

When I lose focus from the table columns, I want to check their values. I created a demo to demonstrate this concept for better understanding. You can view it by following this link: http://jsbin.com/oqeral/16/edit In my implementation, if a column's ...