views:

476

answers:

1

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

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.

+2  A: 

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.

Mark B
was about to post that. +1
thephpdeveloper
Out of interest, what if we do not pay attention to efficiency, are the other way without checking the length property or using any "normal" boolean operations? Are there a way to do that using only jQuery and function chaining? My curiosity organ is itching (-.
Audrius
Not that I'm aware of, other than the solution you posted (removing first whether it exists or not then re-adding). There's some discussion here though: http://stackoverflow.com/questions/31044/is-there-an-exists-function-for-jquery
Mark B
Ok, thanks for link.
Audrius