Close and reopen a tag around a specific word

I need to close the <span> before the word "hello" and reopen it immediately after clicking the button.

Here is the fiddle

This is my code:

 <span class="border"> border Hello border border </span> <div> <span class="button">Style me !</span> </div> 

jQuery:

 $('.button').click(function () { $('.border').each(function () { var t = $(this).text(); var s = t.split('Hello').join('</span>Hello<span class="border">'); $(this).html(s) }); }); 

HTML output that I got after clicking .button :

 <span class="border"> border Hello<span class="border"> border border </span> 

And I want to get:

 <span class="border"> border </span>Hello<span class="border"> border border </span> 

Why .join n't the .join function .join tag </span> ?

+6
source share
3 answers

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

+7
source

You cannot change the dom structure as a string.

 $('.button').click(function () { $('.border').replaceWith(function () { var parts = $(this).text().split('Hello'); return '<span class="border">' + parts.join('</span>Hello<span class="border">') + '</span>'; }); }); 

Demo: Fiddle

+2
source

You can replace the word "Hello" with your desired string

  $('.button').click(function () { $('.border').each(function () { var t = $(this).text(); var s = t.replace('Hello', '</span>Hello<span class="border">'); $(this).html(s) }); }); 
0
source

All Articles