Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations IamaSherpa on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Dynamically adding <span> in the middle of a paragraph

Status
Not open for further replies.

jkalb32

Programmer
Apr 2, 2007
5
US
What is the best way to dynamically add a <span> tag to a word in the middle of a paragraph inside <p>????
 
Here is a quick example that I came up with to show one way to do this:
Code:
<html>
<head>
<title>Wrapping a span tag demo</title>
<style type="text/css">
	span {
		color: red;
	}
</style>
<script type="text/javascript">
	function insertSpan(word) {
		var re = new RegExp(word,"gi");
		var paragraphs = document.getElementsByTagName('p');
		for (var loop=0,max=paragraphs.length; loop<max; loop++) {
			var paragraph = paragraphs[loop];
			var words = paragraph.innerHTML;
			words = words.replace(re,'<span>'+word+'</span>');
			paragraph.innerHTML = words;
		}
	}
</script>
</head>
<body onload="insertSpan('woolly')">
	<p>The woolly cat sat on the woolly mat and was happy.</p>
</body>
</html>
I have left the code as verbose as possible so you can follow it and unravel it a little bit [smile]

Cheers,
Jeff

[tt]Jeff's Page @ Code Couch
[/tt]

What is Javascript? FAQ216-6094
 
How did this work out for you? It's polite to reply when someone helps you out. Maybe you missed this reply.

Looking at your profile, you have posted 3 questions and not replied (or acknowledged) the feedback others have given - yet.

This site thrives on people helping one another for no form of payment... except thanks. If you don't provide any feedback... don't expect people to go out of their way to help.

Cheers,
Jeff

[tt]Jeff's Page @ Code Couch
[/tt]

What is Javascript? FAQ216-6094
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top