Monday, May 13, 2024
 Popular · Latest · Hot · Upcoming
72
rated 0 times [  78] [ 6]  / answers: 1 / hits: 55803  / 15 Years ago, fri, october 30, 2009, 12:00:00

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.


More From » jquery

 Answers
7

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!


[#98414] Tuesday, October 27, 2009, 15 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
lucianom

Total Points: 601
Total Questions: 98
Total Answers: 109

Location: Kenya
Member since Fri, Dec 23, 2022
1 Year ago
lucianom questions
Tue, Feb 22, 22, 00:00, 2 Years ago
Wed, May 5, 21, 00:00, 3 Years ago
Sun, Jan 24, 21, 00:00, 3 Years ago
Sat, Aug 15, 20, 00:00, 4 Years ago
Mon, Jun 22, 20, 00:00, 4 Years ago
;