I want to create a new div(row) which contains everytime 4 <a>
(incl. the children of <a>
) tags and starting before the first <a>
tag.
Here is how it looks right now:
<div class="container" id="cont">
<div class="row">
<div class="col-lg-12">
<h1 class="page-header">My Page Header</h1>
</div>
</div>
<a>....</a>
<a>....</a>
<a>....</a>
<a>....</a>
<a>....</a>
<a>....</a>
<a>....</a>
<a>....</a>
</div>
But it should look like this:
<div class="container" id="cont">
<div class="row">
<div class="col-lg-12">
<h1 class="page-header">My Page Header</h1>
</div>
</div>
<div class="row">
<a>....</a>
<a>....</a>
<a>....</a>
<a>....</a>
</div>
<div class="row">
<a>....</a>
<a>....</a>
<a>....</a>
<a>....</a>
</div>
</div>
and so on...The <a>
tags do not have any ID's they only contain some Images.
How do I manage to do this with JQuery?
Keep in mind I am completely unexperienced with JQuery!
My code so far:
$("#cont").children("a").each(function(index) {
if (index % 4 == 0) {
$('<div id="abc' + index + '">Test</div>').insertAfter(".row");
}
});
Try this, DEMO
$(document).ready(function () {
var mycontent = '';
$("#cont").children("a").each(function (index) {
var cc = $(this).html();
if (index % 4 == 0) {
mycontent += '</div><div id="abc' + index + '">';
mycontent += "<a href=''>" + $(this).html() + "</a>";
}
else {
mycontent += "<a href=''>" + $(this).html() + "</a>";
}
});
$("#cont").find('a').remove();
$("#cont:first .row").append(mycontent);
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<div class="container" id="cont">
<div class="row">
<div class="col-lg-12">
<h1 class="page-header">My Page Header</h1>
</div>
</div>
<a>....</a>
<a>....</a>
<a>....</a>
<a>....</a>
<a>....</a>
<a>....</a>
<a>....</a>
<a>....</a>
<a>....</a>
<a>....</a>
<a>....</a>
<a>....</a>
<a>....</a>
<a>....</a>
<a>....</a>
</div>