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,


Solution 1:

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 :)

Solution 2:

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.

Solution 3:

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

Solution 4:

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

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