I need to close a <span>
tag before the word "hello" and reopen it just after when a button is clicked.
Here is a 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)
});
});
The HTML output I have after clicking .button
is :
<span class="border">
border Hello<span class="border"> border border
</span>
And the output I want is :
<span class="border">
border </span>Hello<span class="border"> border border
</span>
Why isn't the .join
function inserting the </span>
closing tag?
You can modify the dom structure like a string, but you'd have to target the parent element as you can't 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
Note that this works with the example, but if the parent has other elements as well, it can cause issues, and I would strongly suggest finding another way to get the result you're looking for other than closing and opening elements in the middle etc.
EDIT:
Here's another way of doing it, this doesn't affect the parent at all, and is much neater.
It uses outerHTML
to get the surrounding tags as well, that way no partial elements are inserted, but both opening and closing tags are part of the strings passed
$('.button').click(function () {
$('.border').each(function () {
this.outerHTML = this.outerHTML.split('Hello').join('</span>Hello<span class="border">');
});
});
FIDDLE
or the even neater jQuery version
$('.button').click(function () {
$('.border').prop('outerHTML', function(_, html) {
return html.split('Hello').join('</span>Hello<span class="border">');
});
});
FIDDLE
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With