JQuery: expand an element in an HTML string

http://jsfiddle.net/vol7ron/vZLnr/

I am trying to find a better way to expand an HTML string (like an AJAX response) without first attaching it to the document. Also, what is best for memory management?

HTML

  • <div class="label">Start With:</div>
    <pre id="original"></pre>
    
    <div class="label">What Wanted:</div>
    <pre id="wanted"><div>foo</div><div>bar</div></pre>
    
    <hr />
    
    <div class="label">Attempt: .find()</div>
    <pre id="find"></pre>
    
    <div class="label">Attempt: .closest()</div>
    <pre id="closest"></pre>
    

CSS

  • .label    { font       : italic bold 11px Georgia;   margin    : 1em 0 .5em; }
    pre       { border     : 1px solid black;            padding   : 1em;        }
    hr        { margin     : 1.5em 0 1em; }
    
    #original { background : #eee; }
    #wanted   { background : #def; }
    

Javascript

  •    var $html= "<pre><div>foo</div></pre><pre><div>bar</div></pre>";
    
       // No Changes
       jQuery('#original').html($html);
    
    
       // Find
       var $find = jQuery($html).find('*').unwrap();
       jQuery('#find').html($find);
    
    
       // Closest
       var $closest = jQuery($html).closest('pre').unwrap().html();
       jQuery('#closest').html($closest);
    
    
       // Wrapped
       var $pre = jQuery('pre', jQuery($html).wrap('<div />').parent() );
       $pre.each(function(){
                    jQuery('#wrapped').append(jQuery(this).html());
                });
    
       //=========== Prettify Output ===========
       var $wanted = jQuery('#wanted').html();
       jQuery('pre').not('#wanted, #original, #original *')
                    .each(function(){
                      var t = jQuery(this);
                      t.css({background: t.html()==$wanted?'#efe':'#fee'});
                    });
    

Edit

  • The method .find()needs some work as it removes containers with spaces. Imagine <pre><span>Code</span> <span>Here</span></pre>which will turn into <span>Code</span><span>Here</span>(discarded space).
+5
source share
2 answers

, , , , , ( , <, ). , 0 , , . 0, . , , . 1 ( ).

, , javascript .

, .

+1

, , .

  • .html() HTML,

  • .find() -, node.

, HTML, .

, :

jQuery($html).filter('pre').children('div').appendTo('#wanted');

.filter() , .

DOM , .appendTo().

+1

All Articles