Home > other >  jQuery add another html tag to an existing tag
jQuery add another html tag to an existing tag

Time:01-09

I have this code from the browser console that is coming from Javascript of datatables plugin (All codes are shortened):

<div  id="mytable_length">
<label>
"عرض "
<select name="mytable_length" aria-controls="mytable" ></select>
 "نتائج"
</label>
</div>

and underneath of this code I have this code (All codes are shortened):

<div id="mytable_filter" >
<label>
"بحث: "
<input type="search"  placeholder="" aria-controls="mytable">
    </label>
    </div>

This is a picture taken from the browser console just to make things clear https://i.stack.imgur.com/UeLz9.png

Now I need to remove the parent tag <div id="mytable_filter" > and take/move the child tags with elements label and input and add them to/underneath <div id="mytable_length"> using jQuery. So the final code will be:

<div  id="mytable_length">
<label>
"عرض "
<select name="mytable_length" aria-controls="mytable" ></select>
 "نتائج"
</label>
<label>
"بحث: "
<input type="search"  placeholder="" aria-controls="mytable">
    </label>
</div>

using jQuery, what I did so far is:

$(document).ready(function(){
    $('#mytable').DataTable({
        initComplete: function () {
            $('.dataTables_filter').remove();
        },
    });
});

but this will only remove <div id="mytable_filter" > with its child tags, and that's not what I need. How can I do this?

CodePudding user response:

I need to remove the parent tag <div id="mytable_filter" > and take/move the child tags with elements label and input and add them to/underneath <div id="mytable_length">

Appending nodes to a given container is a basic operation in jQuery. Select the nodes, use .appendTo(), done.

$(function () {
    $('#mytable').DataTable({
        initComplete: function () {
            $('.dataTables_filter').children().appendTo('#mytable_length');
            $('.dataTables_filter').remove();
        },
    });
});

A DOM node can only have one parent. If you append it to a different parent, it will effectively be removed from its current parent.

  •  Tags:  
  • Related