9

i am a beginner to java script.i do the bellow code for changing the text color into red using java script.But it doesn't work.what is the error in my code?

<!DOCTYPE html>
<html>
<head>
<script>
function display()
{
var col=document.getElementById("demo").innerHTML;
col.style.color="red";
}
</script>
</head>
<body>

<h1>My First JavaScript</h1>
<p id="demo">click on the button bellow.....</p>

<button onclick="display()">Display</button>

</body>
</html> 
0

5 Answers 5

14

Remove innerHTML from var col=document.getElementById("demo").innerHTML;

<!DOCTYPE html>
<html>
<head>
<script>
function display()
{
var col=document.getElementById("demo");
col.style.color="#FF0000";
}
</script>
</head>
<body>

<h1>My First JavaScript</h1>
<p id="demo">click on the button below.....</p>

<button onclick="display()">Display</button>

</body>
</html>
Sign up to request clarification or add additional context in comments.

Comments

7

Dont use the innerHTML, it returns a String.

Use the style on the object itself.

Check out it working: JsFiddle

1 Comment

just use: function display() { var col=document.getElementById("demo"); col.style.color="red"; }
3

You can try this ...

document.getElementById('demo').style.color = '#FF0000';

Comments

1

Replace this code:

function display()
{
var col=document.getElementById("demo").innerHTML;
col.style.color="red";
}

with this:

function display()
{
var col=document.getElementById("demo");
col.style.color="red";
}

Inner html would contain the html inside the demo tag, but you need to refer to the tag itself.

Comments

0

<!DOCTYPE html>
<html>
<head>
<script>
function display()
{
document.getElementById("demo").style.color="red";
}
</script>
</head>
<body>

<h1>Your Fixed JavaScript</h1>
<p id="demo">click on the button bellow.....</p>

<button onclick="display()">Display</button>

</body>
</html>

Here's the fixed one I just made the change of the words turn red because it wasn't

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.