jervis
jervis

Reputation: 151

How do i correctly search and replace for strings in a HTML-Document with javascript and DOM?

Let's say i have a line in a HTML-File looking like this:

this is <br>a <b>test</b>

I want to find this string (the complete line) by using javascript and for example put:

<font color="..."></font> around it.

around it.

Actually i'm iterating over all text nodes in the DOM structure, but the text is splitted in these nodes, so i think this is the wrong way.

If i iterate over the element nodes i can use textContent perfectly for searching, but not for replacing/changing because the HTML-tags are completely missing.

So what's the correct way to do something like this?

Upvotes: 2

Views: 80

Answers (1)

Renato Galvones
Renato Galvones

Reputation: 555

I think you can achieve your goal by doing some RegExp on the parent node.

If your not familiarized with RegExp, here some nice reference:

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp

Hope it helps.

EDIT:

var text = "<ul><li>1</li><li>2</li><li>3</li></ul><br>bla bla this is <br>a <b>test</b> <br>";
var result = text.match(/(this.*<\/b>)/i);
console.log(result);

In action:

http://jsfiddle.net/G2e5k/

Upvotes: 1

Related Questions