Reputation: 68036
How can I find out if a certain element has another element as a child? And if it doesn't, append a new one to it and then return it.
I tried it with:
var myel = ($('> div.my', this).length > 0)
? $('> div.my', this)
: $(this).append('<div class="my"></div>').css('opacity', 0);
but even though it creates my element if it doesn't exist, it doesn't return it...
Upvotes: 19
Views: 24561
Reputation: 1840
Late I know, but a different approach, adding syntactic sugar and making things legible IMO:
function ifNotExists($x){
if(!$x || $x.length === 0) return { create : function(newX){ return newX; }}
else return { create : function(){ return $x } };
}
//usage:
$someDiv.append(ifNotExists("div.child").create("<div class='child'>"));
Upvotes: 0
Reputation: 13198
How about this?
var myel = $('> div.my', this).length ? $('> div.my', this) : $('<div class="my"></div>').css('opacity', 0).appendTo(this);
Upvotes: 22
Reputation: 9037
Similar to Alastair's method, but using filters:
$('div.outerDiv:not(:has(div.my))').each(function(){
$('<div class="my"></div>')
.appendTo(this)
.css('opacity', 0);
});
Upvotes: 3
Reputation: 19601
This is how I would do it:
var myDivs = $('div.container').children('div.my');
if(myDivs.length === 0){
myDivs = $('<div class="my"></div> ')
.appendTo('div.container')
.css('opacity', 0);
}
My reasoning is that you only need to query the children once, so if there is a lot of children, this will save some time.
Also, if there is no children, then you create one, appendTo
the container, perform css and then return it.
Upvotes: 5