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> <span id="1">Barack</span> <span id="2">Obama</span> <span id="3">xx</span> <span id="4">Barack</span> <span id="5">Obama</span> <span id="6">Barack</span> <span id="7">Obama</span><br> <br> <span id="8">sdsds</span> <span id="9">Barack</span> <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> <span id="1">Barack</span> <span id="2">Obama</span> <span id="3">xx</span> <span id="4">Barack</span> <span id="5">Obama</span> <span id="6">Barack</span> <span id="7">Obama</span> <span id="8">sdsds</span> <span id="9">Barack</span> <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.