简体   繁体   中英

Remove Specific Content from div with jQuery?

Can you remove specific content from an element with jQuery?

So for example, if I had

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

could I turn it into

<p>this is a test</p>

with jQuery (or any Javascript)

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

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

wont work

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

Do it like so:

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

where elem is the reference to the DOM element which text content you want to modify.

You don't need jQuery for this.

First get your element's HTML (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 remove exactly "Hello, " do this:

str = str.substring(7);

If you want everything after the coma use:

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

And set its HTML back with:

p.innerHTML = str;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM