jQuery: Difference between .html().length and .length
Blogs20112011-09-02
in jQuery, it is very common to do the following 2 judges:
- Does the element exists?
e.g., if aexists, then add message to it; if not, create it then add message. In such case, use $(E).length.- Does the element include something or empty?
e.g., there is a, how to know this div includes elements, html or just empty? In such case, use $(E).html().length.The 2 judges are different, they are used in different case.
In case 1:
//if exist? use $(element).length. $('#divid').hover(function() { if($('#msg').length) { $('#msg').show('fast'); } else { $('<span id="msg">some messages...</span>').appendTo('#divid'); } }, function() { if($('#msg').length && $('#msg').is(':visible')) { $('#msg').hide('fast'); } });In case 2:
//Does element empty or include html? if($("#divid").html().length==0) { $("#divid").load('script.php?action=list').fadeIn(100); }We can always use the following simple way to check:
var t = $(the_element); alert('['+$(t).html()+'],'+$(t).length+','+$(t).html().length); - Does the element include something or empty?
