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...
How about this?
var myel = $('> div.my', this).length ? $('> div.my', this) : $('<div class="my"></div>').css('opacity', 0).appendTo(this);
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.
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);
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With