Select element matching ID after a certain element, or create it if it doesn't exist
<div id="foo">
FOO
</div>
<div id="nextfoo">开发者_如何学C</div>
How can I select #nextfoo from a $('#foo').each()...
function, and if it doesn't exist then create it ?
var nextFoo= $('#nextfoo');
if (!nextFoo.length){
nextFoo=$('<div id="nextfoo"/>').insertAfter('#foo');
}
you mean something like this?
First of all ids should be unique on a given page. So there is no need to have each
loop on $("#foo")
You can use jQuery next
method to get the next element(#nextfoo). If it is not present then you can insert it using jQuery after
method. Try this
if(!$("#foo").next().is('#nextfoo')){
$("#foo").after('div id="nextfoo" />');
}
else{//It exists
var nextfoo = $("#foo").next();
}
As others have said, every id should be unique. So if is this structure which you are looking to have repeated...
<div class="foo"></div>
<div class="nextfoo"></div>
... and you are missing some 'nextfoo' classes after your 'foos' then you can do something like the following:
$('.foo').each(function() {
if (!$(this).next().hasClass('nextfoo')) {
$(this).after('<div id="nextfoo">nextfoo 2</div>');
}
});
Here is a demo of this in action.
精彩评论