William Jiang

JavaScript,PHP,Node,Perl,LAMP Web Developer – http://williamjxj.com; https://github.com/williamjxj?tab=repositories

jQuery: Difference between .html().length and .length

in jQuery, it is very common to do the following 2 judges:

  1. Does the element exists?
    e.g., if a <div> exists, then add message to it; if not, create it then add message. In such case, use $(E).length.
  2. Does the element include something or empty?
    e.g., there is a <div>, 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);
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: