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.
There are two ways to check whether an element in the HTML document exists or not using jQuery. Approach 1: Using the length property in jQuery. If the element exists, then the length property will return the total count of the matched elements with the specified selector.
In jQuery, you don't need to be worried about checking the existence of any element. If element does not exists, jQuery will do nothing. jQuery provides length property for every element which returns 0 if element doesn't exists else length of the element.
contains DOM API, you can check for the presence of any element in the page (currently in the DOM) quite easily: document. body. contains(YOUR_ELEMENT_HERE);
To add a new element to the HTML DOM, you must create the element (element node) first, and then append it to an existing element.
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!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With