2017-12-25 11 views
0

私はHtml文字列を持っています。これをhtmlに解析して、preタグを削除してその子要素を削除します。html文字列内の要素をjQueryで削除する方法

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); 

が、それはどんなpreタグを見つけることができないことを意味し、このアラート私0: は、私はこれを試してみました。 誰でも自分のコードに何が問題なのか教えていただけますか?

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>

答えて

3

<pre>は、文字列のルートレベルにあるので、それは働いていません。その場合のfilter()動作しますが、それは一般的にあなたが他の容器に文字列を挿入し、あなたが心配する必要はありませんので、他の容器にfind()を使用したいあなたの要素

の別の内部にネストされた場合には、別の<pre>を見つけられないでしょう入れ子レベルについてあなたは、あなたがpreタグを取得するためにfind()を使用することができ、DOM要素に追加することで、あなたのHTML文字列を使用してDOMツリーを作成する必要が

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>

+0

短い説明は、この良い答えを完了します... –

1

素子。

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>

関連する問題