简体   繁体   中英

Select p tag, but exclude some children

I am using jquery to select a section of copy:

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

(num is declared elsewhere and is not an issue).

This selects all content within the p tag (obviously), however the p tags that I am selecting have nested a tags and strong tags. Is there a way of selecting the p tag and excluding the strong tag for example. I have tried the below code:

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

But this selects all the children elements (excluding strong) but not the content of the actual p tag.

Any ideas would be welcome!

Thanks in advance!

Edit - Example requested:

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

Preferably return this:

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

or this:

This is some content which I would like to include. <a href="#">also keep this</a>
var p = $('.main-content p:nth-child('+num+')').clone();
p.find('*:not(a)').remove();
var your_string = p.html();

or you can specify exact tags to remove:

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

You can use regular expressions:

 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> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM