I have some HTML like this:
<span>Header Here</span>
<span>Content Here</span>
<span>Another Header</span>
<span>Some Other Content Here</span>
As you can see the HTML isn't really formatted in a very accessible way, and unfortunately I can't change the output, what I need to do is wrap every 2 spans with a div so the output becomes this:
<div class="row">
<span>Header Here</span>
<span>Content Here</span>
</div>
<div class="row offsetRow">
<span>Another Header</span>
<span>Some Other Content Here</span>
</div>
The offsetRow class will repeat every other row.
Is this even possible in jQuery?
You can use .wrapAll()
like
var $els = $('span'); for (var i = 0; i < $els.length; i += 2) { $els.slice(i, i + 2).wrapAll('<div class="row ' + (i > 0 && i % 2 == 0 && i % 4 != 0 ? 'offsetRow' : '') + '"></div>') }
.row { color: grey } .offsetRow { background-color: lightblue; } span { border: 1px solid red; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <span>Header Here</span> <span>Content Here</span> <span>Another Header</span> <span>Another Header</span> <span>Another Header</span> <span>Another Header</span> <span>Another Header</span> <span>Another Header</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.