Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery: add dom element if it does not exist

Tags:

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.

like image 401
Audrius Avatar asked Oct 30 '09 10:10

Audrius


People also ask

How do you check if an element does not exist in jQuery?

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.

Does not exist in jQuery?

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.

How do you check if a element is present or not in Dom?

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

How do you add an element to the DOM?

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.


1 Answers

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!

like image 191
Mark Bell Avatar answered Oct 14 '22 02:10

Mark Bell