Search code examples
jquerylistmoveprepend

Move a list inside the parent tag using jquery


I have a list in this fiddle which is drawn as,

<li>List 1</li>
<li>List 2</li>
<li>List 3</li>

How can I add its parent tag, ie, move that list to an ordered list tag using jquery so that it becomes,

<ol>
<li>List 1</li>
<li>List 2</li>
<li>List 3</li>
</ol>

Solution

  • You can use the wrapAll method:

    $('li').wrapAll('<ol></ol>');
    

    Or in vanilla JavaScript:

    var ol = document.createElement('ol'),
        lis = document.querySelectorAll('li');
    
    lis.item(0).parentNode.appendChild(ol);
    
    [].forEach.call(lis, function(e) {
       ol.appendChild(e);
    });
    

    Note that you shouldn't use JavaScript for fixing markup! Fix whatever generates the markup. If it's a html document, open it in your favorite text editor, and fix the markup like a gentleman.