Swati Sharma
Swati Sharma

Reputation: 709

How to change the content of the Span using jQuery?

<span class="stbuttontext" st_page="home">ShareThis</span>

I want to change "Share This" to "Share",

please let me know the solution.

thanksl,

Upvotes: 67

Views: 93864

Answers (4)

Christopher Altman
Christopher Altman

Reputation: 4896

This is my way of thinking about when to use .html() vs. .text().

Use .html() when you want to add styling with html tags to the text you are replacing, like:

$('.stbuttontext').html('<strong>Share</strong>');

This is ofter useful when you are displaying an error message because you may want to add a class to change the color of the text.

$('#error').html('<span class="errortext red"><strong>Error:</strong> <em>Fix your email address</em></span>');`

Use .text() when you simply want to change the text.

So if you did the above example with .text:

$('#error').text('<span class="errortext red"><strong>Error:</strong> <em>Fix your email address</em></span>');

The text the user will see on the web page is (without the spaces in the tags, I could not figure out how to get it to work with this markdown editor).

< span class="errortext red">< strong>Error: < em>Fix your email address< /em>< /span>

and that text is not red, or have bold or italic text.

Upvotes: 23

Egor Pavlikhin
Egor Pavlikhin

Reputation: 18011

$('.stbuttontext').html('Share');

Will change the text of all spans with the class stbuttontext.

Upvotes: 3

Sarfraz
Sarfraz

Reputation: 382909

You can do with either:

$('.stbuttontext').text('Share');

for textual content or

$('.stbuttontext').html('Share');

for html contents.

In your case however, the first statement should be fine :)

Upvotes: 121

Fitzchak Yitzchaki
Fitzchak Yitzchaki

Reputation: 9163

$('.stbuttontext').html('Share');

Upvotes: 7

Related Questions