$(function () { console.log('test start'); $('.mytest').click(function () { var html = '<button>test</button>'; $(this).after(html); }); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <button class="mytest">test1</button> <button class="mytest">test2</button> <button class="mytest">test3</button> 

When you click '<button>test</button>' again, you need to replace with the same element '<button>test</button>' and not add a new '<button>test</button>' .

  • 2
    replaced by what? - Grundy
  • What means replaced? would be replaced by a new element or would the contents of the span be replaced? - ampawd
  • Click execute script. You will see that when you click on the button, the word test is added. This word should be added when clicking to replace the previous one if it has already been added - Serge Esmanovich
  • replaceWith - Grundy

1 answer 1

You can delete the previous <span> before adding a new one:

 $(function() { var i = 0; $('.mytest').click(function() { $(this).next('span').remove(); var html = '<span>test' + i + '</span>'; $(this).after(html); i++; }); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <button class="mytest">test1</button> <button class="mytest">test2</button> <button class="mytest">test3</button> 

In general, to change the text inside <span> it is better not to recreate <span> each time, but simply to change the text in the once created:

 $(function () { var i = 0; var $buttons = $('.mytest'); var html = '<span></span>'; $buttons.after(html); $buttons.on("click", function() { var text = 'test' + i; $(this).next().text(text); i++; }); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <button class="mytest">test1</button> <button class="mytest">test2</button> <button class="mytest">test3</button> 

  • What if instead of a span there is a button? isn't there any more elegant solution =) - Serge Esmanovich
  • @SergeEsmanovich you add not only <span> -s, or are you talking about a situation where <span> has never been added? - Regent
  • yes, when instead of span we add a button, the first click will remove the button following the element that was clicked - Serge Esmanovich
  • @SergeEsmanovich there is a more elegant solution: stop adding <span> every time, creating them when the page loads. And then just change the text in them. But I don’t know why you create the <span> - maybe you need to create it with every click. - Regent
  • one
    @SergeEsmanovich no, not deleted. 'span' inside .next('span') is written for a reason. But your change of the text of the question a couple of minutes ago, a cardinal change in the decision, is generally a “cognizable case”. So things are not done. - Regent