Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 633
Sandeep Roy Avatar asked Mar 15 '26 17:03

Sandeep Roy


2 Answers

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.

like image 172
Oskar Szura Avatar answered Mar 17 '26 06:03

Oskar Szura


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

x.style.color='red';
like image 32
Tuğca Eker Avatar answered Mar 17 '26 08:03

Tuğca Eker