选择p标签,但排除一些孩子

时间:2016-11-21 22:27:31

标签: javascript jquery html css

我正在使用jquery来选择一部分副本:

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 个答案:

答案 0 :(得分: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();

答案 1 :(得分: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>