Create a dropdown menu in jQuery by using the prepend trigger

I'm attempting to utilize jQuery to prepend a trigger to a menu and then have that trigger toggle child elements. Unfortunately, the code below is not opening the sub menus when using jQuery prepend. Can anyone provide a suggestion for a fix?

HTML

<ul>
  <li class="menu-item-has-children">Item 1</li>
    <ul class="sub-menu">
      <li>Sub Item 1</li>
      <li>Sub Item 2</li>
      <li class="menu-item-has-children">Sub Item 3</li>
        <ul class="sub-menu">
          <li>Sub Sub Item 1</li>
          <li>Sub Sub Item 2</li>
          <li>Sub Sub Item 3</li>
          <li>Sub Sub Item 4</li>
          <li>Sub Sub Item 5</li>
        </ul>
      <li>Sub Item 4</li>
      <li>Sub Item 5</li>
    </ul>
</ul>

CSS

ul li {
 list-style-type:none;
}
.open {
  width:20px;
  height:20px;
  background-color:red;
  color:#fff;
  display:block;
  cursor:pointer;
  text-align:center;
}
.sub-menu {
  display:none;
}

JS

jQuery(document).ready(function() {
jQuery('.menu-item-has-children').prepend ('<a class="open">+</a>');
    jQuery('.open').click(function () {
        jQuery(this).next('.sub-menu').toggle();
  });
});

JS FIDDLE

Thanks!

Answer №1

The main issue lies not in your JavaScript code, but in your HTML structure.

As mentioned by Joseph Marikle: Your ul

allows for zero or more <li> elements, which can also contain nested <ol> or <ul> elements.

However, the ul should not have any child elements other than li.

In this particular case, the element .open does not have a sibling, which is why .next() cannot locate .sub-menu.

If you nest your inner ul inside the li.menu-item-has-children, the JavaScript will function correctly:

jQuery(document).ready(function() {
  jQuery('.menu-item-has-children').prepend('<a class="open">+</a>');
  jQuery('.open').click(function() {
    jQuery(this).next('.sub-menu').toggle();
  });
});
ul li {
  list-style-type: none;
}

.open {
  width: 20px;
  height: 20px;
  background-color: red;
  color: #fff;
  display: block;
  cursor: pointer;
  text-align: center;
}

.sub-menu {
  display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul>
  <li class="menu-item-has-children">Item 1
    <ul class="sub-menu">
      <li>Sub Item 1</li>
      <li class="menu-item-has-children">Sub Item 3
        <ul class="sub-menu">
          <li>Sub Sub Item 1</li>
        </ul>
      </li>
      <li>Sub Item 4</li>
    </ul>
  </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

Working with extensive amounts of HTML in JavaScript

Is there a way to dynamically load large amounts of HTML content in JavaScript? I'm struggling to figure out how to insert all the HTML content into the designated space within the JavaScript code. If anyone knows a different approach or solution, ple ...

Is it possible to launch an Electron application by clicking a run button in the VSCode

I'm new to using VSCode and am currently working on an HTML5 app with Electron. I'm finding it cumbersome to switch between windows and enter a command each time I want to test my application. Is there a way to configure VSCode to run my Electron ...

Clearing data validation in HTML after an error has been resolved.Is there a way to clear

I need some help with a cloud page I am creating. I have implemented an alphabetic data validation in HTML to only allow users to input letters, which is working as expected. However, the issue I am currently facing is that the data validation error messa ...

Is your attention on directing an inline jQuery UI Datepicker towards utilizing keyboard shortcuts effectively?

After scouring the web for a solution or example without success so far, I am turning to this community for help. I have found that jQuery UI offers convenient keyboard shortcuts for the Datepicker widget, but they only seem to function if the widget is a ...

Display the output of JSON.stringify in a neatly formatted table

After sending my table data to the database using ajax, I am now trying to retrieve it by clicking on the open button. $.ajax({ type: "POST", url: "http://localhost/./Service/GetPageInfo", dataType: "json", ...

What is the best way to have a text field automatically insert a hyphen after specific numbers?

Is there a way to make a text field insert hyphens automatically after certain numbers? For example, when typing a date like 20120212, could we have the input automatically formatted with hyphens after the first 4 digits and the second two, so it displays ...

An efficient approach to populating a dropdown menu with array values using jquery

Here is an array that I am working with: var serviceArray= new Array("Living Room","Dining Room","Bedroom(s)","Family Room","Kitchen","Den","Hallway(s)","Ste(s)","Bathroom","Landing(s)"); I am looking to populate the options of a select tag with these v ...

Experience the potential of HTML5 by playing dual audio MKV/AVI videos

After conducting some research, it seems that Chrome has the necessary codecs to play MKV videos. However, I have yet to come across any information on how to select audio tracks in MKV and AVI files using Javascript/HTML5. Does anyone have any insight in ...

Align the text field value with the corresponding tooltip content in Vuetify

<v-col class="d-flex align-center"> <v-tooltip bottom> <template v-slot:activator="{ on }"> <v-text-field v-on="on" :value="info.payeeNo" den ...

The Issue with Non-Functional Links in Nivo Slider

Currently facing an issue with the Nivo Slider as it no longer links to any of the photos in the slider. Initially, I had 14 pictures linked to a post with a full embedded gallery inside. The problem arose when using a "fixed" size for the gallery, which d ...

Exploring the power of Sitecore in combination with Solr search functionality and Autos

We've integrated Solr Search with Sitecore 8.1 and MVC, but we're encountering difficulties with the Auto complete/Auto Suggestion feature in the search text box. Challenge: The search results are not displaying as quickly as expected, leading t ...

Is it possible for me to set my HTML body class as ".body" in CSS?

CSS .body { background: linear-gradient(-45deg, rgb(255, 0, 0), rgba(216, 29, 29, 0.856), #fdfdfdd7, #234cd5, #ffffff); background-size: 400% 400%; background-repeat:no-repeat; animation: gradient 35s ease infinite; height: 100vh; } HT ...

Error encountered while using Jquery's .each() method on a DOM element and attempting to

Trying to utilize the each() function on my DOM to dynamically retrieve a field, I encountered an issue with the following code: var new_entry = new Object(); $('div[name="declaration-line-entry"]').each(function () { new_entry.name = $(this ...

Guide to Embedding an Image in a List in HTML

How do I resize an image according to the size specified in CSS, and ensure that it fits within a list of items where each item consists of both an image and a name? Currently, my code only displays the image in its original size. for(var i =0; i< o ...

What is the best way to ensure that two divs have aligned bottom edges?

I have a set of div containers positioned in different columns within a grid layout. I am looking for a way to identify the containers where the bottom edge is less than 50px higher than any other container, and adjust their heights so they align perfectly ...

Angular 8 implementation of a responsive readonly input text field styled with Bootstrap 4

I want to make the input text read-only using Bootstrap. After some research on the Bootstrap website, I discovered that the form-control-plaintext class can be used for this purpose. <input type="text" readonly class="form-control-plaintext" id="stat ...

Adding conditional href based on a specific criteria to an <a> tag in AngularJs

I have been working on a menu list where some menus contain URLs and others do not. When a menu item includes a URL, the href attribute is displayed, otherwise just the span tag is shown. I tried checking it like this but ended up with href="#" when the me ...

Create a dynamic HTML table as the page loads

Customize for vhinn This is the desired output: I am currently attempting to dynamically create an HTML table on pageload using variables retrieved from a database. Here is a simple example of HTML code: http://jsfiddle.net/jdv590/daCum/1/ Code snippet ...

Tips for replacing spaces with &nbsp; in a string using ReactJS and displaying it in HTML

<div className="mt-2 font-sidebar capitalize"> {item.title} </div> item.title can vary and be any string retrieved from the backend, such as "all products", "most liked", "featured items", etc. I am looking for a solution to subst ...

"Implementing jQuery to trigger a click event on each anchor tag with a unique callback function based on

My issue arises from the following code segment: for(j=0; j<conn_nodes.length; j++) { var content_all_connections = ""; var node_id = conn_nodes[j]['conn_node_id']); var a_id = "#" + node_id_slice; content_all_connections = " ...