I try to find and replace text (using jQuery). Actually I'm trying to add a span element around the text. I should also be able to remove the span again without losing the text inside.
For example, let's say I have the following situation to start with:
<span>This is a span element</span>
And I want to be able to do this dynamically using jQuery/JavaScript:
<span>This is a <span class="marked">span</span> element</span>
I should also be able to remove the span.marked and get back to the first result.
The problem however is that I want to do this on all text inside a container with multiple children and subchildren and so on.
The code I got so far will do the following and that is not what I want:
<<span class="marked">span</span>>This is a <span class="marked">span</<span class="marked">span</span> element</span>
I want to do this for ALL text on the page, not just the first it finds.
EDIT: my code so far for doing this:
var re = new RegExp(word, 'g');
$('.container').html($('.container').html().replace(re, '<span class="marked">' + word + '</span>'));
word is a string with the text to wrap spans around.
We can replace HTML elements using the jQuery . replaceWith() method. With the jQuery replaceWith() method, we can replace each element in the set of matched elements with the provided new content and return the set of elements that were removed.
To wrap a search string in html you can use something like this:
$('span:contains("word")').html().replace('word', '<span class="marked">word</span>');
and to remove it, you can use something like this:
$('span:contains("word")').html().replace('<span class="marked">word</span>', 'word');
Yes this is a pretty crude way of doing it but it should work.
EDIT: as pointed out by @user3558931, the word needs to be a variable.
To wrap a search string in html you can use something like this:
$('span:contains("' + str + '")').html().replace(str, '<span class="marked">' + str + '</span>');
and to remove it, you can use something like this:
$('span:contains("' + str + '")').html().replace('<span class="marked">' + str + '</span>', str);
EDIT: A glitch in the above code, see the fixed code in this fiddle: http://jsfiddle.net/thePav/7TNk6/21/
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