Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jquery: remove content between elements

Tags:

jquery

I have the following HTML but I can't modify it manually.

<p class="class_1">
    <span class="support">Phonenr:</span> 
    1231231231 <span class="country">country1</span><br>
    312313123 <span class="country">country2</span><br>
    31231312 <span class="country">country3</span><br>
</p>

I want to remove this part:

<span class="country">country1</span><br>
312313123 <span class="country">country2</span><br>
31231312 <span class="country">country3</span><br>

so that the result is:

<p class="class_1">
    <span class="support">Phonenr:</span> 
    1231231231
</p>
like image 716
Pr3tor Avatar asked Dec 09 '25 00:12

Pr3tor


1 Answers

Try:

$('p.class_1').contents(':gt(2)').remove();

jsFiddle example

Just to add a quick explanation as to why this works, .contents() returns elements as well as text and comment nodes. So for your example, .contents() contains 12 elements:

0: text (a newline)
1: span.support
2: text (1231231231 )
3: span.country
4: br
5: text (312313123 )
6: span.country
7: br
8: text (31231312 )
9: span.country
10: br
11: text (a newline)

You want to get rid of everything after node two, so .contents(':gt(2)').remove() does the job nicely. And as Felix pointed out, since .contents() is sensitive to all text, including spaces, if the content changes you'd have to modify my answer accordingly.

like image 59
j08691 Avatar answered Dec 11 '25 21:12

j08691



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!