开发者

jQuery - create element if doesn't exist - a shorter way

开发者 https://www.devze.com 2023-03-14 18:14 出处:网络
How can I find out if a certain element has another element as a child? And if it doesn\'t, append a new one t开发者_Go百科o it and then return it.

How can I find out if a certain element has another element as a child? And if it doesn't, append a new one t开发者_Go百科o 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);
});


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'>"));
0

精彩评论

暂无评论...
验证码 换一张
取 消