Remove specific content from div using jQuery?

Is it possible to remove specific content from an element using jQuery?

So, for example, if I had

<p>Hello, this is a test</p> 

Can i turn it into

 <p>this is a test</p> 

with jQuery (or any javascript)

Please keep in mind that I just want to delete "Hello", so

 $(p).innerHTML("this is a test"); 

does not work

+4
source share
3 answers
 var str = $('p').text() str.replace('Hello,',''); $('p').text(str); 

For more information, visit: https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/String/replace

+6
source

Do it like this:

 $( elem ).text(function ( i, txt ) { return txt.replace( 'Hello,', '' ); }); 

where elem is a reference to the DOM element whose text you want to change.

+6
source

You do not need jQuery for this.

First get the HTML code of the element (if you have only one of them, use jQuery.each otherwise):

 var p = document.getElementsByTagName('p')[0]; var str = p.innerHTML; 

Then, if you want to delete "Hello" exactly, do the following:

 str = str.substring(7); 

If you want everything after using a coma:

 str = str.split(',', 2)[1]; 

And set its HTML back:

 p.innerHTML = str; 
+1
source

All Articles