2016-11-21 28 views
1

我使用jQuery來選擇副本部分:選擇p標籤,但排除一些孩子

str = '.main-content p:nth-child('+num+')'; 
string = jQuery(str).html(); 

(NUM在別處聲明,是不是一個問題)。

這將選擇p標籤內的所有內容(顯然),但是我選擇的p標籤嵌套了標籤和強標籤。 有沒有辦法選擇p標籤,例如不包括強標籤。我曾嘗試下面的代碼:

str = '.main-content p:nth-child('+num+') :not(strong)'; 

但這種選擇所有子元素(不包括強)但不實際的p標籤的內容。

任何想法都會受到歡迎!

在此先感謝!

編輯 - 舉例要求:

<p><strong>Content that I want to ignore</strong> This is some content which I would like to include. <a href="#">also keep this</a></p> 

最好返回此:

<p>This is some content which I would like to include. <a href="#">also keep this</a></p> 

或本:

This is some content which I would like to include. <a href="#">also keep this</a> 
+2

你能告訴例如HTML和期望的輸出嗎? – Stuart

+0

向您想要修改的元素添加一個類。 –

+0

你能更具體嗎?這將如何幫助完全?感謝您的輸入! – samisonline

回答

3
var p = $('.main-content p:nth-child('+num+')').clone(); 
p.find('*:not(a)').remove(); 
var your_string = p.html(); 

,或者您可以指定確切標記刪除:

p.find('strong, b, i').remove(); 
+0

非常感謝!像魅力一樣工作! – samisonline

0

您可以使用正則表達式:

var str = $('p').html(); 
 
str = str.replace(/<strong>[^<]*<\/strong>/gi,''); 
 
console.log(str.trim());
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 

 
<p><strong>Content that I want to ignore</strong> This is some content which I would like to include. <a href="#">also keep this</a></p>