Reputation: 682
I need to get for example all div's data-id
's and place a new div with data-id="6"
in between data-id="3"
and data-id="9"
.
The new data-id can be with an id of 1 too, so there's no div before it, but it needs to be before data-id 2
(if it exists, if not then before the next highest number)
<div class="container">
<div data-id="1"></div>
<div data-id="2"></div>
<div data-id="5"></div>
<div data-id="7"></div>
<div data-id="11"></div>
</div>
And I need to add a div with data-id="9"
in between 7 and 11.
I'm still learning jQuery so I don't really have any clue how to achieve this. I tried with insertBefore()
but it doesn't work like I want it to. It only works when the new div is data-id="10"
and data-id="11"
exists in the container.
Upvotes: 1
Views: 1266
Reputation: 144689
var $container = $('.container'),
$d = $container.find('div'),
$n = $('<div>', { data: { id: 9 }, text: 9 });
// filter the element with smaller data-id
var $a = $d.filter(function () {
return $(this).data('id') < 9;
}).last();
// If an element with smaller data-id exists
// insert the element after it
if ($a.length) $a.after($n);
// Otherwise prepend it to the container
else $container.prepend($n);
Upvotes: 2
Reputation: 150050
Here's the first way that came to mind:
function addDiv(id, content) {
var $newDiv = $("<div></div>").attr("data-id",id).html(content),
$container = $("div.container"),
$divs = $container.find("div[data-id]"),
inserted = false;
$divs.each(function(i) {
if (id < +$(this).attr("data-id")){
$newDiv.insertBefore(this);
inserted = true;
return false;
}
});
if (!inserted)
$newDiv.appendTo($container);
}
addDiv(9,"whatever");
Upvotes: 0