How to remove text inside an element with jQuery?

22,794

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.

Share:
22,794
Javier Villanueva
Author by

Javier Villanueva

I'm a UK based Magento certified developer currently working at Media Lounge. I specialise in e-commerce solutions but I like to keep up to date with all things involving PHP, WordPress and front end development. Get in touch if you want to work together.

Updated on February 03, 2020

Comments

  • Javier Villanueva
    Javier Villanueva about 4 years

    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!

  • genesis
    genesis almost 13 years
  • Javier Villanueva
    Javier Villanueva almost 13 years
    No luck :( it does make sense though
  • Javier Villanueva
    Javier Villanueva almost 13 years
    Thanks! I ended up using $('ul li').contents().filter(function() { return this.nodeType == Node.TEXT_NODE; }).remove();
  • megawac
    megawac about 10 years
    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