Javascript Code to Change Text Color of HTML elements

by top54u.com 26 Jun, 2008

Javascript DOM also allows to change the Text color of HTML elements dynamically. Text color of HTML element can be changed using document.getElementById method that takes the parameter as value of id attribute of any particular HTML element whose text color you want to change. You can change the text color of HTML div element, span tag or paragraph tag easily by specifying the unique values for their id attribute that can be accessed by using the getElementById method of document object of Javascript. style object of the getElementById method provides the reference to various CSS properties that can be changed dynamically using Javascript.

 

Syntax of style object of getElementById to change text color

 

document. getElementById("id") .style. color = "value";

 

You can pass the id of any HTML div element, span element or paragraph element that exits on your HTML document. The value should be a color name or hex color code that could be assigned to the text using this Javascript code.

 

Javascript Example of Change Text Color of HTML elements

 

<html>

<head>

<title>Javascript Change Text Color Style</title>

 

<script language="javascript" type="text/javascript">

function changeDivTextColor()

{

document.getElementById('div1').style.color = 'red';

}

 

function changeSpanTextColor()

{

document.getElementById('span1').style.color = '#0000ff';

}

 

function changeParaTextColor()

{

document.getElementById('para1').style.color = 'darkgreen';

}

</script>

</head>

 

<body>

<div id="div1">

Javascript will change the text color of this Div tag dynamically.

</div>

<p id="para1">

This text is inside the HTML paragraph p tag.

<span id="span1">

This text inside the HTML span element placed inline to parapgraph p tag.

</span>

</p>

<input type="button" value="Change Div text color" onclick="changeDivTextColor()" />&nbsp;&nbsp;

<input type="button" value="Change Span text color" onclick="changeSpanTextColor()" />&nbsp;&nbsp;

<input type="button" value="Change Paragraph text color" onclick="changeParaTextColor()" />

</body>

</html>

 

Above Javascript example shows how to change the font color of HTML elements link Div, span and paragraph.

Spotlight.....

Be the first to rate this post

  • Currently 0/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

Tags: , , , , , , , , , , , ,

Add comment


(Will show your Gravatar icon)  

  Country flag

[b][/b] - [i][/i] - [u][/u]- [quote][/quote]



Live preview

10/11/2008 3:26:07 AM




related videos.....
recent posts.....
top54u ezines.....