Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery: Find text and replace with HTML

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.

like image 602
Wouter Avatar asked May 20 '14 12:05

Wouter


People also ask

How to replace html in jQuery?

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.


1 Answers

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/

like image 148
PavKR Avatar answered Sep 20 '22 11:09

PavKR