如何使用jQuery删除html字符串中的元素

问题描述 投票:0回答:3

我有一个Html字符串,我想将其解析为HTML,然后删除任何pre标签,它的孩子。我试过这个:

HTMLString = "<p>a paragraph</p><p>second Paragraph</p><pre>&lt;script&gt;&nbsp;&nbsp;&nbsp;&nbsp;function (){&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;something();&nbsp;&nbsp;&nbsp;&nbsp;}&lt;/script&gt;</pre>";
var $jQueryObject = $($.parseHTML(HTMLString));
alert($jQueryObject.find('pre').length);

但这提醒我0这意味着它找不到任何pre标签。谁能告诉我我的代码有什么问题?

this is my fiddle

HTMLString = "<p>a paragraph</p><p>second Paragraph</p><pre>&lt;script&gt;&nbsp;&nbsp;&nbsp;&nbsp;function (){&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;something();&nbsp;&nbsp;&nbsp;&nbsp;}&lt;/script&gt;</pre>";
    var $jQueryObject = $($.parseHTML(HTMLString));
alert($jQueryObject.find('pre').length);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
javascript jquery html-parsing
3个回答
3
投票

它不起作用,因为<pre>在字符串的根级别。对于那种情况filter()工作,但它不会找到另一个<pre>如果它嵌套在你的另一个元素

通常,您希望将字符串插入另一个容器并在另一个容器上使用find(),因此您无需担心嵌套级别。

HTMLString = "<p>a paragraph</p><p>second Paragraph</p><pre>&lt;script&gt;&nbsp;&nbsp;&nbsp;&nbsp;function (){&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;something();&nbsp;&nbsp;&nbsp;&nbsp;}&lt;/script&gt;</pre>";

//changing your code to use `filter()` 
var $jQueryObject = $($.parseHTML(HTMLString));
console.log('Filter length:', $jQueryObject.filter('pre').length)

// Using `find()` within another container
var $container = $('<div>').append(HTMLString);
console.log('Find length:', $container.find('pre').length)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>

5
投票

HTMLString = "<p>a paragraph</p><p>second Paragraph</p><pre>&lt;script&gt;&nbsp;&nbsp;&nbsp;&nbsp;function (){&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;something();&nbsp;&nbsp;&nbsp;&nbsp;}&lt;/script&gt;</pre>";
    var $jQueryObject = $("<div/>").html(HTMLString);
    console.log("Befor Remove tag: "+ $jQueryObject.find('pre').length);
    $jQueryObject.find('pre').remove();
    console.log("After Remove tag: "+ $jQueryObject.find('pre').length);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>

1
投票

您需要通过附加到DOM元素来使用HTML字符串创建DOM树,然后您可以使用find()来获取pre标记元素。

var HTMLString = "<p>a paragraph</p><p>second Paragraph</p><pre>&lt;script&gt;&nbsp;&nbsp;&nbsp;&nbsp;function (){&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;something();&nbsp;&nbsp;&nbsp;&nbsp;}&lt;/script&gt;</pre>";
var $jQueryObject = $('<div>').append($(HTMLString));
console.log($jQueryObject.find('pre').length);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
© www.soinside.com 2019 - 2024. All rights reserved.