Split heading into different colors for each word

Hi guys,

I’m trying to create a graphic style where every other word of a heading is a different color.

This code below works but now I want to do the same thing and there is more than one h3 on the page. Of course this code concatenates them together, can anybody write me something which applies these colors to each h3 independently.



var form_heading = $.trim($(".form_heading h3").text()); // get all text inside a heading
var $new_form_heading = "<h3>";  // create a new string ready to replace the old heading

var parts = form_heading.split(" ");  // break up heading into words
for(i = 0; i < parts.length; i++){	  // do the different colors
	if(i % 2 == 0)
	{
	$new_form_heading += " <span style='color:#0000ff'>" + parts[i]  + "</span>";
	}
	else
	{
	 $new_form_heading += " <span style='color:#ff6600'>" + parts[i] + "</span>";
	}	
}
$new_form_heading += "</h3>"; //close tag
$('h3').replaceWith($new_form_heading);

thanks

Silversurfer

This should help you… Note, I am using plain JS here and it’s not fully tested…

Fiddle: http://jsfiddle.net/L2HJb/

<head>
	<style>
		.test1 { color: blue; }
		.test2 { color: red; }
	</style>
</head>
<body>
	<h3>Test this h3 header out</h3>
	<h3>This is another h3 header</h3>
	<h3>And another</h3>
	
	<script>
		var h3 = document.getElementsByTagName('h3'),
			i,
			j,
			parts,
			newH3;
		
		for( i = 0; i < h3.length; i++ ) {
			newH3 = [];
			parts = h3[i].innerHTML.split(' ');
			
			for(j = 0; j < parts.length; j++) {
				newH3.push(
					(j % 2 == 0)
						? ' <span class="test1">' + parts[j] + '</span>'
						: ' <span class="test2">' + parts[j] + '</span>'
				);
			}
			h3[i].innerHTML = newH3.join(' ');
		}		
	</script>
</body>

Hey thanks centered effect,

I liked the use of the outer loop and the join, cool stuff. I really need to learn to use more vanilla js, I am heavily reliant on JQuery. I came up with an alternative using JQuery:



	
$('.form_heading h3').each( function( index ) {
var parts = $.trim($(this).text()).split(" ");
var $new_form_heading ="";
for(i = 0; i < parts.length; i++){	
	if(i % 2 == 0)
	{
	$new_form_heading += " <span style='color:#0000ff'>" + parts[i]  + "</span>";
	}
	else
	{
	 $new_form_heading += " <span style='color:#ff6600'>" + parts[i] + "</span>";
	}	
     }
       $(this).replaceWith($new_form_heading);
});