skip to main | skip to sidebar

Working with HTML Fragments in jQuery
When you are working in jQuery with generated HTML fragments that are returned from AJAX, It is interesting to note these cases..

1) Creating New elements on The Fly

When passing HTML string to jQuery( html ) it will look for HTML tags (ex: <tag ... >) somewhere within the string. Then, it attempts to create new DOM elements as described by the HTML string.

But, be ware of that: in complex HTML strings, some browsers may not generate a DOM that replicates the HTML you provided especially for not well-formed snippets.

Solution, is really simple. First, create a new container div and set its inner HTML with the snippet string then append it to the target element.
$(document).ready(function(){
   // not-well-formed HTML string
   var str = '1<br>2<br>3';

   // Bad: creating new elements
   $(str).appendTo('#output1');

   // Good: using inner HTML
   $('<div/>').html(str).appendTo('#output2');
});

2) Having Images or Iframes in fragments

When you intend to filter out some parts of the HTML snippet before appending it to the DOM, you should note that the web browser will immediately request any images or iframes or scripts it finds in that snippet and certainly slowing down your page loading.
* you can inspect what resources are loaded on web pages using Firebug for FireFox or built-in developer tools in Chrome.

Solution, is to rename the [src] attribute of the img or iframe tags as [tempsrc] using regular-expressions to prevent browser from loading them. Then, when you are finished with filtering out unneeded parts, you can revert it back as it was..

To revert [src] attributes back, you have 2 options:
  1. Using regular expressions again.
  2. After appending the fragment string to a container, you can loop each image/iframe tag using jQuery selectors to revert its [src] attribute as is.
$(document).ready(function(){
   // not-well-formed HTML string
   var str = '1<br>2<br>3<br>'+
            '<img src = [url]>';

   // replace src attributes to tempsrc
   str = str.replace( /\ssrc\s*=/gi , ' tempsrc=' );

   // some manipulations here..

   // **************************** Option 1
   // revert src attributes as is with regex
   str = str.replace( /\stempsrc=/gi , ' src=' );

   // append fragment
   $('<div/>').html(str).appendTo('#output1');

   // **************************** Option 2
   // revert src with jquery after appending the fragment
   var div = $('<div/>').html(str).appendTo('#output2');

   // loop any image, iframe tags to revert src
   $('img,iframe' , div).each(function(){
      var tag = $(this);
      tag.attr('src' , tag.attr('tempsrc'));
   });
});

5 comments

  1. Sandipan Mukherjee // August 9, 2011 3:58:00 AM GMT  

    Nice article...very easy to understand..Keep up the good work.

  2. Rod Knowlton // August 9, 2011 1:46:00 PM GMT  

    In your second example, the word boundary special character '\b' is a zero-width match, so there's no need to capture it and prepend it to your replacement string.

  3. Mike // August 9, 2011 10:35:00 PM GMT  

    @Rod,
    Thanks alot for heads-up, I corrected the code now.
    Officially, You are the first one who had actually read the post :)

  4. Spacebat // August 10, 2011 1:45:00 AM GMT  

    Be aware that if the snippet ever legitimately contains the string " tempsrc=", such as a snippet containing the body of this article itself, then you're in an unhappy place. Never say never.

    To ensure we're only operating on tag attributes named src/tempsrc, I'd rewrite the regexes thus:

    str = str.replace( /(<\w+[^>]*?)(\ssrc\s*=)/gi , '$1 tempsrc=' );

    ...and...

    str = str.replace( /(<\w+[^>]*?)(\stempsrc=)/gi , '$1 src=' );

  5. Mike // August 10, 2011 2:10:00 AM GMT  

    @Spacebat,
    That would not work with working HTML like this
    <img alt="a > b" src="">

    I guess I could change attribute ' tempsrc=' to ' one_in_a_million_src=' to have a chance of 1 in a million of it occurring :)

    Surely, Regular expressions are not for irregular languages like HTML in all situations. But, it should do just fine in that case..

Post a Comment

Thank you for taking the time to comment..
* If you have a tech issue with one of my plugins, you may email me on mike[at]moretechtips.net

Mike

Mike MoreWeb developer, jQuery plugin author, social media fan and Technology Blogger.
My favorite topics are: jQuery , Javascript , ASP.Net , Twitter , Google..
<connect with="me"> </connect>

Subscribe by email

Enter your email address:

or via RSS