Question

Here's my code:

<script type='text/javascript'>
    $(document).ready(function() {
        $('#test').load('http://foobar.com/view.php?id=1186', function() {        
            console.log($('.weekdates'));

            var weeks = $('.weekdates');
            weeks.each(function(i, val) {
                alert($(this).text());                        
            });                              
        });                
    });
</script>

The result of the console.log call is:

[prevObject: b.fn.b.init[1], context: document, selector: ".weekdates", jquery: "1.9.1", constructor: function…]
context: document
length: 0
prevObject: b.fn.b.init[1]
selector: ".weekdates"
__proto__: Object[0]

Any ideas why the elements are not being found in the resulting set? Does it have something to do with loading the HTML dynamically?

Here's the HTML that is added:

<h3 class="weekdates"> 23 de enero -  29 de enero</h3>
Was it helpful?

Solution

To answer your question directly, you can use jquery selectors on HTML returned from an ajax call like so, once you have loaded it into a jQuery object variable...

<script type='text/javascript'>
    $(document).ready(function() {
        $('#test').load('http://foobar.com/view.php?id=1186', function(html) {        
            var $html = $(html);                            
        });                
    });
</script>

But honestly, it seems like you're attempting to loop through results. If this is JSON you're returning from the server, you need $.getJSON()

$.getJSON('http://foobar.com/view.php?id=1186', function(data) {
  $.each(data, function(key, val) {
    // deal with item
  });
});
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top