Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if a div exists with jquery [duplicate]

Yes, I know this has been asked a lot. But, it confuses me, since the results on google for this search show different methods (listed below)

$(document).ready(function() {     if ($('#DivID').length){         alert('Found with Length');     }      if ($('#DivID').length > 0 ) {         alert('Found with Length bigger then Zero');     }      if ($('#DivID') != null ) {         alert('Found with Not Null');     } }); 

Which one of the 3 is the correct way to check if the div exists?

EDIT: It's a pitty to see that people do not want to learn what is the better approach from the three different methods. This question is not actually on "How to check if a div exists" but it's about which method is better, and, if someone could explain, why it it better?

like image 883
Rafael Herscovici Avatar asked Aug 01 '11 13:08

Rafael Herscovici


People also ask

How do you check Div is exist or not in jQuery?

In jQuery, you can use the . length property to check if an element exists. if the element exists, the length property will return the total number of the matched elements. To check if an element which has an id of “div1” exists.

How do you check if the DIV is already exists?

$(document). ready(function() { if ($('#DivID'). length){ alert('Found with Length'); } if ($('#DivID'). length > 0 ) { alert('Found with Length bigger then Zero'); } if ($('#DivID') !=


1 Answers

The first is the most concise, I would go with that. The first two are the same, but the first is just that little bit shorter, so you'll save on bytes. The third is plain wrong, because that condition will always evaluate true because the object will never be null or falsy for that matter.

like image 200
karim79 Avatar answered Oct 14 '22 15:10

karim79