0

The idea is I want to remove the contents of an element, excluding the script elements that are used as Handlebarjs templates.

The example below is fully working, but I am wondering is there a better approach than what I have now? Using .remove() or .empty() as I have done in the example doesn't remove TEXT nodes. Even changing children() => find() doesn't work either.

Example: http://jsfiddle.net/076w8zdm/

// HTML
<div id="content">

<!--This Handlebars template should remain-->
<script type="text/x-handlebars-template">
    <p>{{title}}, {{first_name}}, {{last_name}}</p>
</script>

This text node should be deleted.
<p>This element should be removed too.</p>
</div>
<!--Handlebars template example-->

// JS

// IIFE
; (function ($, undefined) {

console.log('Started');

// Cache the jQuery object
var $content = $('#content');

// Remove the contents of the div#content, but retain the Handlebars template

// $content.empty(); // <<<< Bad, as it removes everything

// These don't work, as the TEXT node isn't removed
// $content.children('*:not(script)').empty()
// $content.children('*:not(script)').remove();

// This works!
$content.contents().filter(function () {
    console.log(this.nodeName);
    // Only filter those which don't have the handlebars type and SCRIPT node name
    return this.nodeName !== 'SCRIPT' || this.type !== 'text/x-handlebars-template';

    // Remove from the DOM
}).remove();

console.log('Finished');

})(jQuery);
guinness
  • 63
  • 6

1 Answers1

1

I'd think this is all you would need:

$('#content').html($('#content script'));

It removes everything except the script contents.

$('#content').html($('#content script'));
console.log($('#content').html());
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="content">
    
    <script type="text/x-handlebars-template">
        <p>{{title}}, {{first_name}}, {{last_name}}</p>
    </script>
    
    This text node should be deleted.
    <p>This element should be removed too.</p>

    <script type="text/x-handlebars-template">
      <p>{{more handebars stuff}}</p>
    </script>

    <p>Another element to remove.</p>    
</div>
Rick Hitchcock
  • 35,202
  • 5
  • 48
  • 79