我有一个Html字符串,我想将其解析为HTML,然后删除任何pre
标签,它的孩子。我试过这个:
HTMLString = "<p>a paragraph</p><p>second Paragraph</p><pre><script> function (){ something(); }</script></pre>";
var $jQueryObject = $($.parseHTML(HTMLString));
alert($jQueryObject.find('pre').length);
但这提醒我0这意味着它找不到任何pre
标签。谁能告诉我我的代码有什么问题?
HTMLString = "<p>a paragraph</p><p>second Paragraph</p><pre><script> function (){ something(); }</script></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>
它不起作用,因为<pre>
在字符串的根级别。对于那种情况filter()
工作,但它不会找到另一个<pre>
如果它嵌套在你的另一个元素
通常,您希望将字符串插入另一个容器并在另一个容器上使用find()
,因此您无需担心嵌套级别。
HTMLString = "<p>a paragraph</p><p>second Paragraph</p><pre><script> function (){ something(); }</script></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>
HTMLString = "<p>a paragraph</p><p>second Paragraph</p><pre><script> function (){ something(); }</script></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>
您需要通过附加到DOM元素来使用HTML字符串创建DOM树,然后您可以使用find()
来获取pre
标记元素。
var HTMLString = "<p>a paragraph</p><p>second Paragraph</p><pre><script> function (){ something(); }</script></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>