3

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.

0

6 Answers 6

7

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.

Sign up to request clarification or add additional context in comments.

3 Comments

Thanks for educating & your time. Please help with a good book for JavaScript for a beginner.
Try this one: shop.oreilly.com/product/9780596517748.do - It think it's the best for start.
Thanks again Sir, have a nice day.
2

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

x.style.color='red';

Comments

2

Syntax mistake

x.style.color='red';

Comments

2

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>

1 Comment

Thanks for educating.
1

Missing quote at the line below.

x.style.color='red';

1 Comment

Thanks you for you time.
1

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>

2 Comments

@Himanshu Sharma assign id value in variable and changed it's style but i try to change without variable name.
this approach seems more compact, i don't have to assign variables, then follow other the procedures. Now simply i can directly assign the changes i want to do. Thanks for educating. I really appreciate.

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.