• Blogs (9)
    • 📱 236 - 992 - 3846

      📧 jxjwilliam@gmail.com

    • Version: ‍🚀 1.1.0
  • jQuery: Difference between .html().length and .length

    Blogs20112011-09-02


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

    1. Does the element exists?
      e.g., if a
      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
      , 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);