I have somewhere on website a specific text, let's say "lollypops", and I want to replace all the occurrences of this string with "marshmellows". The problem is that I don't know where exactly the text is. I know I could do something like:
$(body).html($(body).html().replace('lollypops', 'marshmellows'));
This would probably work, but I need to rewrite as little HTML as I can, so I'm thinking something like:
- search for the string
- find the closest parent element
- rewrite only the closest parent element
- replace this even in attributes, but not all, for example replace it in
class
, but not insrc
In example, I would have structure like this
<body>
<div>
<div>
<p>
<h1>
<a>lollypops</a>
</h1>
</p>
<span>lollypops</span>
</div>
</div>
<p>
<span class="lollypops">Hello, World!</span>
<img src="/lollypops.jpg" alt="Cool image" />
</p>
<body>
In this example, every occurrence of "lollypops" would be replaced, only <img src="...
would remain the same and the only elements that would actually be manipulated would be <a>
and both <span>
s.
Does anybody know how to do this?
You could do something this way:
example: http://jsfiddle.net/steweb/MhQZD/
Why you just don't add a class to the string container and then replace the inner text ? Just like in this example.
HTML:
jQuery:
Below is the code I used to replace some text, with colored text. It's simple, took the text and replace it within an
HTML
tag. It works for each words in that class tags.You could do something like this:
It will be better to mark all tags with text that needs to be examined with a suitable class name.
Also, this may have performance issues. jQuery or javascript in general aren't really suitable for this kind of operations. You are better off doing it server side.