[英]how to remove an element in html string with jQuery
我有一個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>
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>
它不起作用,因為<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>
您需要通過將HTML字符串附加到DOM元素來創建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>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.