Use JavaScript or JQuery to insert an additional set of unordered list items

I have completed the coding for the initial HTML and JavaScript/JQuery components. Now, I am looking to enhance the final common list by wrapping it with an additional UL tag using JavaScript/JQuery. This means that the final common list will be enclosed by two UL elements instead of just one. For example: Desired Result

<ul id="CommonLister">
       <ul> <!--This needs to be added-->
         <li class="columnItem">John</li>
         <li class="columnItem">Mark</li>
       </ul><!--This needs to be added-->
</ul>

Current Code

 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
            <div>
              <ul id="listOne">
                <li class="columnItem">John</li><!--To be moved under CommonLister-->
                <li class="columnItem">James</li>
                <li class="columnItem">Mary</li><!--To be moved under CommonLister-->
              </ul>

          <ul id="listTwo">
            <li class="columnItem">John</li><!--To be moved under CommonLister-->
            <li class="columnItem">Mark</li>
            <li class="columnItem">Mary</li><!--To be moved under CommonLister-->
          </ul>
          <ul id="CommonLister">
            <li class="columnItem">John</li>
            <li class="columnItem">Mark</li>
          </ul>
        </div>

    $(function() {
      $('#run-code').on('click', function(e) {
        e.preventDefault();
        //Not relevant
        var currentItems = {}; //Empty object
        var $mergeColumn = $('#CommonLister'); //Reference to Common List
        $('.columnItem').each(function(i, el) {
          var $el = $(el); 
          if (!currentItems.hasOwnProperty($el.html())) {
            currentItems[$el.html()] = []; 
          }
          currentItems[$el.html()].push(el);
          
        });

        $.each(currentItems, function(name, data) {
          if (data.length > 1) {
            $.each(data, function(i, el) {
              var $el = $(el); 
              if (i == 0) {
                $el.appendTo($mergeColumn);
              } else {
                $el.remove(); 
              } 
            }); 
          } 
        }); 

      }); 
    }); 

    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <button id="run-code" class="btn btn-success">Click Me</button>

    <h4>List 1</h4>
    <ul id="listOne">
      <li class="columnItem">John</li>
      <!--To be moved under CommonLister-->
      <li class="columnItem">James</li>
      <li class="columnItem">Mary</li>
      <!--To be moved under CommonLister-->
    </ul>
    <h4>List 2</h4>
    <ul id="listTwo">
      <li class="columnItem">John</li>
      <!--To be moved under CommonLister-->
      <li class="columnItem">Mark</li>
      <li class="columnItem">Mary</li>
      <!--To be moved under CommonLister-->
    </ul>
    <h4>Common List</h4>
    <ul id="CommonLister"> 
    <!--Additional ul will be inserted here-->
    </ul>

Answer №1

It is considered improper to nest a ul element directly within another ul element, but if necessary, you can utilize jQuery's wrapAll function:

$( "li" ).wrapAll( "<ul></ul>" );

To view an example on how this works, visit this JSFiddle link: https://jsfiddle.net/9xLt6d9f/

Answer №2

While I understand charlietfl's concerns about the approach, to address your query, one effective method of dealing with this incorrectly formatted HTML code would be to manually insert it into your original file. Consider using the following code snippet at the end of your file:

<h4>Common List</h4>
<ul id="CommonLister">
  <ul id="CommonListerSub"> 
<!--Extra ul will be added here-->
  </ul>
</ul>

Next, make a simple adjustment in your code:

var $mergeColumn = $('#CommonListerSub'); //Common list reference

This modification will ensure that the list items are displayed under the nested ul tags.

I trust this solution proves satisfactory. Should you encounter any issues, kindly specify any additional constraints you may have and consider providing the link to the page outlining the necessary template or format specifications.

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

A step-by-step guide to displaying API data in a React frontend using functional components

I've managed to create a backend API using Node+Express+MSSQL and tested the routes with POSTMAN. However, I'm facing challenges when trying to display the data on the front-end using React Functional components/hooks. I'm unsure if I'm ...

barchart rendered in SVG without the use of any external libraries

Creating a stacked barchart with SVG and HTML without relying on any third-party library has been quite a challenge. Despite searching extensively online, I have not come across a single resource that demonstrates how to build a stacked bar chart using pla ...

Ensuring the input box value is up-to-date with jQuery validation

Currently, I am utilizing jQuery v1.9.1 in combination with jQuery-validate v1.9 to validate a user-provided id using the remote method. The main objective is to verify if this id exists within a database. However, there seems to be an issue with the json ...

Prevent reloading the page when adding a flash element using JavaScript (jQuery)

Here is the function I am working with: function onVideo(vchat, idUser){ $('#videollamada').html('<div class="videollamada">'+ '<div align="right">'+ ...

Setting up npm packages for a Node application

Currently working on developing an npm package for testing purposes and looking to incorporate TypeScript. However, the creation of a node_modules folder is unnecessary. Is there a way to install npm dependencies without generating the node_modules folde ...

Switches in a React-Native ListView are not refreshing properly

Situation: I encountered an issue with a ListView of Switches Problem: The Switches are not changing state when pressed. When debugging, each switch appears to be checked momentarily after the setValue function is called, but then reverts back to unchecked ...

What could be causing the hover effect to malfunction in this code snippet?

I have been working on creating a hover effect for a list of items where an underline emerges from the center. While I have done something similar in the past, there seems to be an issue preventing it from working properly this time. I have included the HT ...

Transferring Image through Email using AJAX Technology

By using the following code snippet, I have successfully managed to send an email with an attached image from a different server: <$php $to = "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="225b4d575062474f434b4e0c414d4f"&g ...

Make sure to keep checkboxes selected after they have been submitted

UPDATE: I'm trying to figure out how to keep all the checkboxes checked even after submitting and reloading the page. Currently, they get reset :/ Below is the form code I am working with: <form action="" method="post" id="filtre_form"> <h ...

Triggering a JavaScript function upon the alteration of a Dojo auto-complete widget's value

I'm encountering an issue with calling a javascript function when the value of a Dojo auto completer changes. Despite trying to call the function through the "onChange" attribute, it doesn't work as expected. Within the javascript function, my ...

Next.js fails to properly render external links when utilizing the Link component

It was quite surprising to discover that a basic Link component doesn't function as expected in Next.js when attempting to use it with an external URL and HTML Button tag within. Here is my attempt at solving this issue: Attempt 1: <Link href="h ...

javascriptcode to execute before loading google maps

I am facing an issue with displaying markers on Google Maps. The problem arises when the array with latitude and longitude values is constructed through an Ajax request. Due to the map being loaded before the initialization of the array, I am unable to see ...

Encountering issues with multiple arguments in ajax within a C# MVC application - Further details included

There seems to be a missing piece in my code. Here's my controller method public void SubmitSweep(int personID, int DD, int MM, int YYYY, int hh, int mm, int dealId) Here's how I define my button <button id="submit@(person.Id)" clas ...

Struggling to process AJAX request

Trying to manually create an AJAX request. I have the following code on the client side: function saveBatterySpecs(id) { var url = '@Url.Action("SaveBatterySpecs", "Catalog")'; $.ajax({ type: "post", ...

Having trouble displaying DIV Content with CSS through printing

<script type="text/javascript"> function PrintElem(elem) { Popup($(elem).html()); } function Popup(data) { var mywindow = window.open('', 'mydiv', 'height=550,width=750'); mywindow.doc ...

What is the best way to notify an XML file using jQuery?

I am encountering an issue with a login api when trying to send an xml document. The error occurs when including '<?', but I need to send the whole XML with it. Can someone assist me in sending the complete XML using a different method or type ...

Unusual behavior of the `map` function in Firefox's JavaScript

Here's an interesting observation regarding the behavior of the map function in Firefox. In a particular error scenario on a web application, when Firebug pauses at the error, entering the following code into the Firebug console: ["a", "b", "c", "d" ...

Ways to enhance the functionality of an input component

Within my React app, I have an input component that triggers an onChange event when connected to another component: <input type="text" onChange={onChange} /> Now, I am looking to enhance this input component by incorporating a prop from another com ...

Form data triggering inaccurate results in ajax response

After following online tutorials and seeking help from Stack Overflow, I am still struggling with a strange issue related to AJAX. I appreciate any assistance in solving this problem. I am trying to create a feature where users can search for match result ...

Validation has failed due to a missing title field in MongoDB

I keep getting the error message ValidatorError: Path `title` is required and my data is not getting stored in the database. What could be causing this issue? const mongoose=require('mongoose'); const Articleschema= new mongoose.Schema({ ...