Retaining the content within HTML tags while deleting the tags themselves

I am working on a navigation menu with a mega menu feature. The current markup includes elements for a mega menu, but I need to remove some of these elements when the viewport is small.

Current Markup:

<ul class="megamenu-wrapper">
 <li>
    <ul>
        <li><a href="#">Home</a></li>
        <li><a href="#">About</a></li>
        <li><a href="#">Contact</a></li>
    </ul>
 </li>
 <li> 
    <ul>   
        <li><a href="#">gang</a></li>
        <li><a href="#">menu</a></li>
        <li><a href="#">food</a></li>
    </ul>
 </li>
</ul>

Desired Markup:

<ul class="megamenu-wrapper">

        <li><a href="#">Home</a></li>
        <li><a href="#">About</a></li>
        <li><a href="#">Contact</a></li>

        <li><a href="#">gang</a></li>
        <li><a href="#">menu</a></li>
        <li><a href="#">food</a></li>

</ul>

I currently have two mega-menu-wrapper elements.

Attempted Solution:

var megaContents = $('.megamenu-wrapper li ul').contents();
    $('.megamenu-wrapper li ul').replaceWith( megaContents );

This solution duplicates the list items in both mega menus and causes multiple repetitions of each element. Any help would be greatly appreciated.

Answer №1

Learn

//Find child ul li and add it to main ul
$('.megamenu-wrapper > li > ul > li').appendTo('.megamenu-wrapper');

//Remove li that contain ul
$('.megamenu-wrapper > li:has(ul)').remove();;

$(document).ready(function() {
      $('.megamenu-wrapper > li > ul > li').appendTo('.megamenu-wrapper'); +
      $('.megamenu-wrapper > li:has(ul)').remove();
    });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul class="megamenu-wrapper">
  <li>
    <ul>
      <li><a href="#">Home</a>
      </li>
      <li><a href="#">Abort</a>
      </li>
      <li><a href="#">Contact</a>
      </li>
    </ul>
  </li>
  <li>
    <ul>
      <li><a href="#">gang</a>
      </li>
      <li><a href="#">menu</a>
      </li>
      <li><a href="#">food</a>
      </li>
    </ul>
  </li>
</ul>

use .each() if dealing with multiple menus

$('.megamenu-wrapper') each(function () {
    $(this).find('> li > ul > li').appendTo(this);
    $(this).find(' > li:has(ul)').remove();
});

DEMO

Answer №2

If you want to organize your markup differently, you can utilize the append() function. This function will extract the child elements with anchors and append them as direct descendants of the .megamenu-wrapper element.

To clean up the previous structure, you can use the remove() method to eliminate the old parent li elements that now contain empty child ul elements.

$('.megamenu-wrapper').append($('li:has(a)'));
$('.megamenu-wrapper').children('li:has(ul)').remove();

Update

If you have multiple menus to modify, you can apply the same script above within an each() loop.

$('.megamenu-wrapper').each(function(){
    $(this).append($(this).find('li:has(a)'));
    $(this).children('li:has(ul)').remove();
});

$('.megamenu-wrapper').each(function(){
$(this).append($(this).find('li:has(a)'));

$(this).children('li:has(ul)').remove();

});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<ul class="megamenu-wrapper">
 <li>
    <ul>
        <li><a href="#">Home</a></li>
        <li><a href="#">Abort</a></li>
        <li><a href="#">Contact</a></li>
    </ul>
 </li>
 <li> 
    <ul>   
        <li><a href="#">gang</a></li>
        <li><a href="#">menu</a></li>
        <li><a href="#">food</a></li>
    </ul>
 </li>
</ul>

<ul class="megamenu-wrapper">
 <li>
    <ul>
        <li><a href="#">Home</a></li>
        <li><a href="#">Abort</a></li>
        <li><a href="#">Contact</a></li>
    </ul>
 </li>
 <li> 
    <ul>   
        <li><a href="#">gang</a></li>
        <li><a href="#">menu</a></li>
        <li><a href="#">food</a></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

jquery modal not displaying

My page is designed to display a dialog containing a set of guidelines using a PHP script that determines which guideline(s) should be shown and generates the corresponding div element(s). Afterwards, I utilize a simple $(document).ready( function() { $(" ...

Using v-bind to dynamically set styles in Vue.js

While utilizing v-bind:style to apply dynamic values, I encountered an issue where v-bind:style did not seem to work. However, in the console, I verified that v-bind:style was receiving the correct value (:style='{ color : red (or any other value) }&a ...

Is there anyone available to assist me with resolving this problem regarding Flask?

Recently, I attempted to work on an assignment found on the internet that involved displaying data from Flask to an HTML form. However, I encountered two significant errors in the process: 1) The HTML file rendered in Flask cannot be located. 2) The SQL ta ...

What are the different methods for combining filtered objects or locating two attributes within a collection?

Looking to find an object from an array of objects that has 'age = 1' and 'name = one', here's my approach... Here is how I attempted it: var array = [ {'name':'one', "age":'3'}, {'name& ...

The PopupControlExtender in ajaxToolkit seems to be malfunctioning when used with a textbox that has Tinymce

I recently built a website using ASP.NET, and I have a feature where a small tooltip appears on the right side of a text box when the user focuses on it. To achieve this, I am using the ajaxToolkit:PopupControlExtender in my code. <asp:TextBox ...

How can I prevent users from selecting dates prior to today in a jquery UI datepicker?

I need assistance with creating a hotel reservation system and disabling past dates in jQuery UI datepicker. Below is the code snippet for reference: Calling in .cs public class CheckLookup { [DataType(DataType.Date)] p ...

Select a random object from a document and dispatch it. A Discord bot

I'm looking to enhance my bot by adding a command that retrieves a random quote from a JSON file and displays it in chat. I've already figured out how to do this using an array, but I'm not sure how to pull the quotes from a file. EDIT: ...

Creating textures for a blender model and animating it with JavaScript using Three.js

After successfully animating a model in Blender using bone animation and texturing it with UV mapping, I exported the model with UV and animation checked using the three.js export add-on in Blender. However, I am struggling to load the texture for the anim ...

Personalizing the placement of FontAwesome markers on an Image (map) with absolute positioning

I have successfully positioned markers on a map using FontAwesome to ensure they maintain their relative position when the map is resized. Currently, each marker consists of a number inside a circle created with FontAwesome. However, I am interested in ut ...

Is anyone utilizing PHP variables to control the title of the HTML and the ID of the body element?

I utilize PHP variables to store the title's value and the ID of the body. The latter is a method to show which section of the page the user is currently on (in this case, the "home" section). At the start of my index.php: <?php $title = "New ...

Node.js: A Step-by-Step Guide to Key Press Simulation

Is there a way in nodejs to programmatically press a specific key on the keyboard? For example, after rendering a page, I would like to automatically simulate pressing the f3 button: var express = require('express'); var router = express.Router ...

The getElementByID function will return null in this instance, as it has not been loaded

Hello everyone, I am facing an issue while trying to access an element by its ID in JavaScript as it keeps returning null. This problem arises because the element is not fully loaded when the DOM is initially created, due to a plugin called Restrict Conte ...

Utilizing jQuery's multiselect feature in the user registration form of a web2py website

Is there a way to incorporate jquery.multiselect.js into the db.auth_user table or default/user/register page? I have been trying to figure it out, but not sure how to modify the html page or controller to make it work. auth.settings.extra_fields['au ...

How to make a div stick on horizontal scroll using CSS?

In my web application, there is a division that includes a form structured like the following: https://i.sstatic.net/ydEcn.png The table displaying the results beneath the form is wide, requiring horizontal scrolling to view it in its entirety. Is the ...

JavaScript: Controlling the ability to enter text based on the chosen option from a drop-down menu

After struggling to make my code work, I decided to create a piece of JavaScript to disable a text input when "Cash" payment is selected from the dropdown menu. On the contrary, I aimed to enable the text input if "Credit Card" payment was chosen. Unfortun ...

react-datepicker displaying error message "Preventing default action not possible within a passive event listener invocation"

I've integrated the react-datepicker library in portal mode. While it functions well on browsers, I encounter an error when using mobile browser mode. An issue arises stating: "Unable to preventDefault inside passive event listener invocation" Des ...

Having trouble getting a form to submit to a Rails server using AJAX in IE11 with jQuery

Currently, I'm attempting to transfer data from a form to a Rails server using AJAX. The form consists of two text inputs and one file input. Below is the code for my submit event handler: $("form").on("submit", function(event) { event.preventDefa ...

Field must have a base type specified to proceed

Currently, I am in the process of developing a discord.js bot. The structure I have set up involves a folder that contains all the commands, and when a command is called, index.js directs it to the appropriate file. However, when attempting to run the bot, ...

Utilizing global styles for fonts across Next.js version 13

As I transition a create-react-app to nextjs, I'm navigating the new features and challenges. Nextjs 13 brings in next/font, which seems like a valuable addition as I venture into Next.js for the first time. It makes sense to incorporate it into my wo ...

Have you ever wondered why req.body returns as undefined when using body parser?

Every time I attempt to make a post request, I keep receiving an error message stating that req.body is returning as undefined. Below is the content of my server.js file: import express from 'express'; import bodyParser from 'body-parser&ap ...