[ACCEPTED]-jQuery - create element if doesn't exist - a shorter way-jquery-selectors
Accepted answer
How about this?
var myel = $('> div.my', this).length ? $('> div.my', this) : $('<div class="my"></div>').css('opacity', 0).appendTo(this);
0
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 5 that you only need to query the children 4 once, so if there is a lot of children, this 3 will save some time.
Also, if there is no 2 children, then you create one, appendTo
the container, perform 1 css and then return it.
Similar to Alastair's method, but using 1 filters:
$('div.outerDiv:not(:has(div.my))').each(function(){
$('<div class="my"></div>')
.appendTo(this)
.css('opacity', 0);
});
Late I know, but a different approach, adding 2 syntactic sugar and making things legible 1 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'>"));
Source:
stackoverflow.com
More Related questions
Cookie Warning
We use cookies to improve the performance of the site. By staying on our site, you agree to the terms of use of cookies.