Sandeep Roy
Sandeep Roy

Reputation: 405

JavaScript not changing HTML Styles

I am trying to change the color of my name, by clicking on a button. Here is what I've done till now,

<html>
<head><title></title></head>
<body>
<p id="demo">Sandeep Roy</p> 
<button type="button" onclick="change()">Click</button>
<script>
function change() {
var x=document.getElementById("demo");
x.style.color=red;
}
</script>
</body>
</html>

The expected output is a red font, when 'click' button is clicked.

Unfortunately nothing happens when I do that, i.e same black color font. Please help me educating in this matter.

Upvotes: 3

Views: 4262

Answers (6)

Oskar Szura
Oskar Szura

Reputation: 2549

In the below, you're missing quotas

var x=document.getElementById("demo");
x.style.color=red;

should be

var x=document.getElementById("demo");
x.style.color='red';

besides that - changing the style properties directly may not be the best approach. Instead, change the className, and use CSS to style classes to look different.

Upvotes: 7

Himanshu Sharma
Himanshu Sharma

Reputation: 33

Correct - red color assign as a string name or value(hex color code like '#ff0000') of the color.

Syntax- object.style.color="color|initial|inherit"

x.style.color='red';
x.style.color='#ff0000';

You can see the live demo on Fiddler

<html>
<head><title></title></head>
<body>
<p id="demo">Sandeep Roy</p> 
<button type="button" onclick="change()">Click</button>
<script>
function change() {
var x=document.getElementById("demo");
x.style.color='red';
}
</script>
</body>
</html>

Upvotes: 2

Kamal kannan
Kamal kannan

Reputation: 253

Try this it works,

<html>
<head><title></title></head>
<body>
<p id="demo">Sandeep Roy</p> 
<button type="button" onclick="change()">Click</button>
<script>
function change() {
  document.getElementById("demo").style.color = "red";
}
</script>
</body>
</html>

Upvotes: 1

user6573425
user6573425

Reputation:

Syntax mistake

x.style.color='red';

Upvotes: 2

James
James

Reputation: 1446

Missing quote at the line below.

x.style.color='red';

Upvotes: 1

Tuğca Eker
Tuğca Eker

Reputation: 1493

In this case red is variable. You should use string instead. Use

x.style.color='red';

Upvotes: 2

Related Questions