JSFiddle - React, Tailwind, and code Playground

by roeburg

HTML

<label for="split">
    Enter the index at which you'd like to split the list.
</label>
<input id="split" type="number" min="1" max="20" value="5" />
<button>Click to split</button>
<hr />
<ol id="list">
    <li>item1</li>
    <li>item2</li>
    <li>item3</li>
    <li>item4</li>
    <li>item5</li>
    <li>item6</li>
    <li>item7</li>
    <li>item8</li>
    <li>item9</li>
    <li>item10</li>
    <li>item11</li>
    <li>item12</li>
    <li>item13</li>
    <li>item14</li>
    <li>item15</li>
    <li>item16</li>
    <li>item17</li>
    <li>item18</li>
    <li>item19</li>
    <li>item20</li>
</ol>

CSS

a{
    display: none;
}

JavaScript

// Function usage within a document.ready
$(function () {
    $("button").click(function (){
        /// **** USAGE ****
        $("#list").customSplitList($("#split").val());
        /// **** USAGE ****
        
        $(this).hide();    
    });
});

// Function definition
(function ($) {
    // Function is defined here ...
    $.fn.customSplitList = function (indexToSplit, elementToAddInBetween) {
        // Holds a reference to the element(list)
        var that = this;
        var subList, newList, listLength;

        // Only continue if the element is a derivitive of a list
        if ($(that) && ($(that).is("ul") || $(that).is("ol"))) {

            // Additionally check if the length & the split index is valid
            listLength = $(that).children().length;

            if ($.isNumeric(indexToSplit) && indexToSplit > 0 && indexToSplit < listLength) {
                // Based on list type, create a new empty list
                newList = $($(that).clone(true)).empty();

                while ((subList = this.find('li:gt(' + (indexToSplit - 1) + ')').remove()).length) {
                    newList.append(subList);
                }

                if (elementToAddInBetween && $(elementToAddInBetween)) {
                    that.after(newList);
                    newList.before(elementToAddInBetween);
                } else {
                    that.after(newList);
                }
            }
        }
    };

})(jQuery);