jQuery: filtering HTML results in AJAX

Filtering HTML results with jQuery and AJAX is simple, provided that you understand the basic principles behind the AJAX parsing of an HTML document. When you set the dataType parameter to html using the $.ajax() wrapper method, you're actually telling jQuery to return a full DOM structure that you can traverse with normal jQuery DOM methods. This is made possible by jQuery thanks to its internal selector engine that allows you to treat the returned HTML either as a string or as a DOM structure.

I had to display a list of my recent posts taken from my post page on Html.it. First, I did set up a server-side script to fetch such remote page:

<?php
header('Content-Type: text/html');
$html = file_get_contents('http://blog.html.it/author/gabroman');
echo $html;
?>

The post list is actually made up of several paragraphs with a progressive ID attribute contained within a div with ID content. So what I have to do is simply to search for all the paragraphs with an ID attribute:

$(document).ready(function() {

  $('<ol id="posts"/>').appendTo('#content');
  
  $.ajax({
    type: 'GET',
    dataType: 'html',
    url: 'script.php',
    success: function(html) {
    
      var content = $(html).find('#content');
      var newContent = '';
      
      content.find('p[id]').each(function() {
      
        var $p = $(this);
        var link = $p.find('a');
        var href = link.attr('href');
        var text = link.text();
        
        
        
          newContent += '<li><a href="' + href +
           '">' + text + '</a></li>';
        
       
      
      
      });
      
       $('#posts').html(newContent);
    
    }
    
 });

});

This kind of filtering is really simple but effective. You can see the results in the demo below.

Demo

Live demo

Leave a Reply

Note: Only a member of this blog may post a comment.