Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to remove text inside an element with jQuery?

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!

like image 432
Javier Villanueva Avatar asked Jul 14 '11 08:07

Javier Villanueva


People also ask

How remove and append in jQuery?

jQuery uses: . append(); and . remove(); functions to accomplish this task. We could use these methods to append string or any other html or XML element and also remove string and other html or XML elements from the document.

Why remove function is not working in jQuery?

Your clear() function is not global because it is defined inside your document ready handler, so your onclick="clear()" can't find it. You need to either move the function outside the ready handler (making it global), or, better, bind the click with jQuery: $(document). ready(function(){ $(this).

How do I remove ATTR?

The removeAttr() method is an inbuilt method in jQuery which is used to remove one or more attributes from the selected elements. Parameters: This function accepts single parameter attribute which is mandatory. It is used to specify one or more attributes to remove.

How do I remove an innerHTML element?

innerHTML property innerHTML property will get or set the HTML markup contained within the element. But you can utilize this property to “remove” any elements within the container, by setting the value to an empty string. This property is fully cross-browser, read full docs on innerHTML.


1 Answers

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.

like image 61
DanielB Avatar answered Oct 15 '22 21:10

DanielB