14

I have a script that creates a list of items with a structure like this:

<li>
    <div>Some stuff</div>
    <a href="http://www.mysite.com/">New Item</a> 
    (1 vote)
</li>

I was wondering if there was a way to remove everything outside the <div> and <a> tags, in this case the (1 vote) string, with jQuery or regular javascript.

Thanks in advance!

Javier Villanueva
  • 3,886
  • 13
  • 48
  • 80
  • 1
    This has everything you want: http://stackoverflow.com/questions/298750/how-do-i-select-text-nodes-with-jquery – benhowdle89 Jul 14 '11 at 08:34

3 Answers3

28

This should work.

$("li").contents().filter(function(){ return this.nodeType != 1; }).remove();

or by specifying text nodes explicitly

$("li").contents().filter(function(){ return this.nodeType == 3; }).remove();

See this fiddle.

DanielB
  • 19,910
  • 2
  • 44
  • 50
1
$('li').html($(this).children())

You can try this, it should work. Clean and easy.

megawac
  • 10,953
  • 5
  • 40
  • 61
pjamfaro
  • 23
  • 1
  • 6
  • Interesting idea but html only takes a string. You can do `.empty().append(children)` but you would have to store the children before you do that – megawac Feb 03 '14 at 00:48
0
$('li').not('div,a').text('') 

Try this, untested

Edit

$('li').contents().filter(function(){ return !(this.tagName == 'DIV' 
                                            || this.tagName == 'A');}).remove();
hungryMind
  • 6,931
  • 4
  • 29
  • 45