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.
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, 2020Comments
-
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 almost 13 yearsNope, it does not work: sandbox.phpcode.eu/g/-247fd6d2e7667cb8732e56d5043f96db.php
-
Javier Villanueva almost 13 yearsNo luck :( it does make sense though
-
Javier Villanueva almost 13 yearsThanks! I ended up using
$('ul li').contents().filter(function() { return this.nodeType == Node.TEXT_NODE; }).remove();
-
megawac about 10 yearsInteresting 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