jQuery: add dom element if it does not exist

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