简体   繁体   中英

Create a parent from child elements using javascript

Say i have a list of ids [[1,2],[4,5,6]]

I am trying to create a parent element for each set of ids, say a div

currently its:

<span id="data-inject">
   <br> <br>
    <span id=1>Barack</span>
    <br> <br>
    <span id=2>Obama</span>
    <span id=3>xx</span>
<span>

I would like it to be:

   <span id="data-inject">
   <br> <br>
    <div id=test>
        <span id=1>Barack</span>
        <br> <br>
        <span id=2>Obama</span>
    </div>
    <span id=3>xx</span>
    </span>

is there any way to achieve the same using java script?

 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <span id="data-inject"><br> <br> <span id="0">xx</span>&nbsp;<span id="1">Barack</span>&nbsp;<span id="2">Obama</span>&nbsp;<span id="3">xx</span>&nbsp;<span id="4">Barack</span>&nbsp;<span id="5">Obama</span>&nbsp;<span id="6">Barack</span>&nbsp;<span id="7">Obama</span><br> <br> <span id="8">sdsds</span>&nbsp;<span id="9">Barack</span>&nbsp;<span id="10">Obama</span></span> 

Try this :

$('#data-inject').find('span').slice(0,2).wrapAll('<div id="test"></div>').after(' ');

Here is a Jsfiddle : https://jsfiddle.net/8L1mutxr/

.after(' ')

add spaces after elements. But your HTML is very dirty by the way.

Using jquery you can easily create a new element for each array item and then loop through the inner array to search and append to the newly create item,

the example should be auto explanatory:

 var arr = [[1,2],[4,5,6], [7,8,9,10]] arr.forEach((x, i) => { // we create a parent div for each item var parent = $('<div class="parent'+ i + '"></div>') // we append it $('#data-inject').append(parent) // we loop through inner arrays and append them to newly created 'parent' x.forEach(z => { parent.append( $('#' + z) ) }) }) 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <span id="data-inject"> <span id="0">xx</span>&nbsp; <span id="1">Barack</span>&nbsp; <span id="2">Obama</span>&nbsp; <span id="3">xx</span>&nbsp; <span id="4">Barack</span>&nbsp; <span id="5">Obama</span>&nbsp; <span id="6">Barack</span>&nbsp; <span id="7">Obama</span> <span id="8">sdsds</span>&nbsp; <span id="9">Barack</span>&nbsp; <span id="10">Obama</span> </span> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM