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

DIV collapsing in reverse order from the bottom to the top

Looking for some help on how to create two links that, when clicked, will scroll a hidden <div> up to fill the full height of its parent container. I've been having trouble with the element using the full height of the <BODY> instead. ...

Using the built-in http module in node.js to upload images via multipart/form-data

I have encountered an issue where I need to send two images and an API key as part of a multipart/form-data HTTP request to an API. The images are retrieved from an AWS S3 bucket, which works fine. However, when attempting to send the image data as part ...

Error received when attempting AJAX call with jQuery 1.7.2: NS_ERROR_XPC_NOT_ENOUGH_ARGS

Encountering an issue with jQuery version 1.7.2 and the ajax function. When running the code snippet below, Firefox Firebug console displays the following error: NS_ERROR_XPC_NOT_ENOUGH_ARGS: Not enough arguments [nsIDOMLocation.replace] var wei ...

Having difficulties in Vue while attempting to access a particular row

I encountered an error message stating Uncaught TypeError: snapShotChnaged.forEach is not a function. My goal is to retrieve specific row data, which is why I am utilizing the doc method. retrieveSpecificDonation() { firestore .collection('d ...

Tips on showing binary information as images using extjs 4

As the proud owner of a valid .JPEG image's binary data, I am on a quest to convert this information into an actual viewable image using Python. Seeking advice on how to successfully transform this binary code into a visually appealing .JPEG format w ...

Utilize Electron to extract and render content from a local file into HTML code

I am struggling to find a solution for automatically reading and parsing a local csv file in an electron application. When I use 'fs' to open the file, I can't figure out how to pass the contents into the HTML window. One option is to use a ...

Jquery Parallax causing scrolling problems across different browsers

Could you please take a look at the following link in both Chrome and Firefox? I am encountering some unusual issues. Primary Concern The scrolling function works smoothly in Firefox, but it seems to be malfunctioning in Chrome. Secondary Problem Whe ...

Can you determine the height of an image if only the width and border width are provided?

Currently delving into the world of HTML and CSS, I've successfully configured the img element's width and border width using a style element. However, one aspect that is still puzzling me is how the height is calculated in this scenario. I&apos ...

Instructions for applying a specific style to TextFields using a theme provider

Custom transitions and colors have been added to the textfields using the makeStyles hook in the component. The issue lies in needing to define these customs every time they are used in a component. There is a desire to establish them in the theme provid ...

Exploring ways to access data stored in interconnected models, such as MongoDB and NodeJS

As a newcomer to querying, I attempted a unique exercise to practice but unfortunately did not achieve the desired outcome. I have three models: const userSchema = new Schema({ info1: String, info2: String }, const serviceSchema = new Schema( { name ...

A "Uncaught TypeError" error occurs when trying to execute a function using the dollar sign

After successfully recognizing the hover function, the console displays an error message: Uncaught TypeError: $ is not a function <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script> <script> $(docume ...

What is the cause behind the failure of this regular expression in JavaScript?

I have been struggling to make this code display "matched!" for the specific string. I've tried various methods but nothing seems to be working. Here's the HTML part: <div id="ssn">123-45-6789</div> And here's the JavaScript p ...

How to pass a single value using onClick event without relying on form submission

I prefer to pass a single value instead of multiple putPriority fetch calls. This value will not be inputted by the user directly, but rather passed through an onClick event. For example, I want the onClick to send a specific number to "status" in the fe ...

Troubleshooting Java REST service integration in AngularJS for UPDATE and DELETE operations

After successfully implementing a REST service with Java and testing all HTTP methods using Postman, I decided to explore AngularJS. Upon integrating it to consume the REST service, I encountered issues specifically with the Delete and Put methods not func ...

Transform an item into a map of the item's properties

I am faced with an object containing unknown key/value pairs in this format: myObj = { key_1: value_1, key_2: value_2, key_n: value_n } My goal is to transform it into a dictionary of structured objects like the one below: dictOfStructureObjec ...

Assistance with JavaScript Regular Expressions for formatting BBCode

A few weeks ago, I stumbled upon this regex expression: /([\r\n])|(?:\[([a-z\*]{1,16})(?:=([^\x00-\x1F"'\(\)<>\[\]]{1,256}))?\])|(?:\[\/([a-z]{1,16})\])/ig It's designe ...

Angular router.redirect is not able to pass variables as expected

I am facing an issue with the router redirect and template lifecycle while using Stripe checkout in my Angular 5 project. After a user signs up, I trigger the stripe checkout modal. Once the modal receives a payment source token, I perform some additional ...

Take a custom action once all elements have been rendered with ng-repeat

Looking to manipulate a DIV element generated by ng-repeat: <div ng-repeat="data in info" > <div id='plot_{{data.id}}'></div> </div> Here is the sequence of events: Information added to $scope.info ng-repeat exec ...

using node.js to extract a cookie from a 302 redirect

Need help simulating a login using node.js. The request is a post method and returns a 302 status code. However, when trying to simulate the request in node, I encounter the following error: Error handling unrejected promise: StatusCodeError: 302 Upon i ...

Implementing X.PagedList within a modal pop-up window

I have implemented a modal pop-up on a webpage: ... <div class="modal fade" tabindex="-1" role="dialog" aria-labelledby="companySearchModal" aria-hidden="true" id="companySearchModal"> <div class="modal-dialog" role="document"> ...