tags:

views:

44

answers:

1

Hello,

I would like to count number of elements on remote page: For example remote page:

test.html with following structure

<div id="Layout">
   <div class="product">...</div>
   <div class="product">...</div>
   <div class="product">...</div>
</div>

Then I would like call from test2.html

   <script type="text/javascript">
        $(document).ready(function(){
           $('#result').load('/test.html #Layout product').length();
        });
    </script>

This code is not working. What is the right way to do it? Thank you.

+2  A: 

You need to wait until the elements are actually loaded, you can use the callback function argument of the $.load method:

$(document).ready(function(){
  $('#result').load('/test.html #Layout', function () {
    var products = $('.product', this).length;
    alert(products);
  });
});

Check the above example here.

Also, if you don't want to insert the loaded elements into the DOM, you can load them into a new empty element, for example:

$('<div></div>').load('/test.html #Layout', function () {
  var products = $('.product', this).length;
  alert(products);
});
CMS
Thank you very much. Is is possible not load content of test.html to #result. #result should display only total number of elements from remote page. Thank you again.
mp1
@mp1, you're welcome, for doing that, take my second example and replace `alert(products);` for `$('#result').text(products);`
CMS
@CMS Thank you very much, code works perfectly.
mp1