开发者

jQuery: add dom element if it does not exist

Long question

Is it possible to add a DOM element only if it does not already exists?

Example

I have implemented the requirement like so:

var ins = $("a[@id='iframeUrl']");
ins.siblings('#myIframe:first').remove().end().parent().prepend('<iframe id="myIframe"  src="'+ins.attr("href")+'"></iframe>');开发者_JAVA百科

Is it possible to replace the second line with something more elegant? Like ins.siblings('#myIframe:first').is().not().parent().prepend ...

I could check ins.siblings('#myIframe:first').length and then add IFrame, but the curiosity took over and I'm trying to do that in the least amount of statements possible.


I think the way you suggested (counting length) is the most efficient way, even if it does involve a bit more code:

var ins = $("a[@id='iframeUrl']");

if(ins.siblings('#myIframe:first').length == 0)
    ins.parent().prepend('<iframe id="myIframe" src="'+ins.attr("href")+'"></iframe>');

Also, the :first selector would be redundant here as there should only ever be one element with that ID, so:

var ins = $("a[@id='iframeUrl']");

if($('#myIframe').length == 0)
    ins.parent().prepend('<iframe id="myIframe" src="'+ins.attr("href")+'"></iframe>');

would also work.

Edit: as Fydo mentions in the comments, the length check can also be shortened, so the tersest form would be:

var ins = $("a[@id='iframeUrl']");

if(!$('#myIframe').length)
    ins.parent().prepend('<iframe id="myIframe" src="'+ins.attr("href")+'"></iframe>');

Note the exclamation mark before the selector in the if condition!


I needed something similar and I always try to reduce the amount of code, so I wrote this little helper function (TypeScript).

$.fn.getOrAddChild = function(selector: string, html: string): JQuery {
  var $parent = <JQuery>this;
  if (!$parent.length)
    throw new Error("Parent is empty");
  var $child = $parent.children(selector);
  if (!$child.length)
    $child = $(html).appendTo($parent);
  return $child;
}

// Usage
$("div.myDiv").getOrAddChild("div.myChildDiv", "<div class='myChildDiv'/>");
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜