【问题标题】:Remove contents of an element excluding certain nodes names/types删除元素的内容,不包括某些节点名称/类型
【发布时间】:2015-10-24 11:44:43
【问题描述】:

这个想法是我想删除一个元素的内容,不包括用作 Handlebarjs 模板的脚本元素。

下面的示例完全有效,但我想知道是否有比我现在更好的方法?像我在示例中所做的那样使用 .remove() 或 .empty() 不会删除 TEXT 节点。即使更改 children() => find() 也不起作用。

示例: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);

【问题讨论】:

    标签: jquery dom textnode


    【解决方案1】:

    我想这就是你所需要的:

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

    它会删除除脚本内容之外的所有内容。

    $('#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>

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-06-12
      • 2015-03-01
      • 1970-01-01
      • 2011-09-27
      • 1970-01-01
      • 2013-05-01
      相关资源
      最近更新 更多