You can change the dom structure as a string, but you need to target the parent element as you cannot insert partial elements
$('.button').click(function () { $('.border').each(function () { var t = $(this).parent().html(); var s = t.split('Hello').join('</span>Hello<span class="border">'); $(this).parent().html(s) }); });
Fiddle
Please note that this works with an example, but if the parent has other elements, this can cause problems, and I highly recommend finding another way to get the result you are looking for, except closing and opening the elements in the middle, etc.
EDIT:
Here is another way to do this, it does not affect the parent at all, and is far ahead.
It uses outerHTML to get the surrounding tags, so no partial elements are inserted, but both the opening and closing tags are part of the passed strings
$('.button').click(function () { $('.border').each(function () { this.outerHTML = this.outerHTML.split('Hello').join('</span>Hello<span class="border">'); }); });
Fiddle
or even a tidier version of jQuery
$('.button').click(function () { $('.border').prop('outerHTML', function(_, html) { return html.split('Hello').join('</span>Hello<span class="border">'); }); });
Fiddle
source share