DEV Community

Cover image for Change span text jQuery - [SOLVED]
ProgrammerMoney.com
ProgrammerMoney.com

Posted on • Edited on

Change span text jQuery - [SOLVED]

TL;DR Summary

Changing span text in jQuery is very easy and there are 3 ways to go about it:
(also let's assume we have HTML looking like this)

<span id="one">first text</span><br />
<span id="two">second text</span><br />
<span id="three">third text</span>
Enter fullscreen mode Exit fullscreen mode

1) Change single element by ID

// change by ID
$('#two').text('jQuery text');

// change by index
$('span').eq(1).text('jQuery text');
Enter fullscreen mode Exit fullscreen mode

Here all elements are selected with $('span') but you can select one by index like this .eq(1) (index starting from zero obviously).

change span text jQuery

2) Change all the elements - same text

$('span').text('jQuery text');
Enter fullscreen mode Exit fullscreen mode

And the result will be something like this:
change span text jQuery - the same

3) Change all the elements - different text

$('span').each((index, element) => {
  $(element).text(`jQuery text - ${index}`);
});
Enter fullscreen mode Exit fullscreen mode

And here is how it looks like:
change span text jQuery - unique

And that's it.
Now you know how to change span text with jQuery.

Until next time,

Will

P.S. check out my Algo-Trading Journey articles

Top comments (0)