简体   繁体   中英

Trying to change element by Id - Not Working

I have tried various things, but I can't get the last three lines to work.

Any idea's why this will not change the font to red, italics, center align?

This is the first day of my course, I have no lecturer to ask, and there is no explanation given.

document.bgColor = "blue";
document.fgColor = "white";

var myDemo = document.getElementById("demo");
myDemo.innerHTML = Date();
document.getElementById("demo").fgColor = "red";
myDemo.fontStyle = "italics";
myDemo.textAlign = "center";

The fgColor & bgColor properties are deprecated and not supported in all browsers. You could use color & backgroundColor properties to change the color and the background color.

All the style related properties belongs to the 'style' property of the element. We cannot set the css properties directly on the element. We have to set it on the element style property.

fgColor & bgColor : These feature are no longer recommended. Though some browsers might still support it, it may have already been removed from the relevant web standards, may be in the process of being dropped, or may only be kept for compatibility purposes. Avoid using it, and update existing code if possible. Be aware that this feature may cease to work at any time.

 document.body.style.color = "green" document.body.style.backgroundColor = "black"; function chnageColor() { var myDemo = document.getElementById("demo"); myDemo.innerHTML = Date(); myDemo.style.color = "red"; myDemo.style.fontStyle = "italic"; myDemo.style.textAlign = "center"; }
 <div id="demo"> Some Text </div> <button type="button" onclick="chnageColor()">Change color</button>

You need to use style property of DOM object to access any styling attribute.

 var myDemo = document.getElementById("demo"); myDemo.innerHTML = Date(); myDemo.style.fontStyle = "italic"; myDemo.style.textAlign = "center";
 <div id="demo">Testing</div>

You have a typo in italics and also properties you trying to change are set in element.style instead of element itself.

document.bgColor = "blue";
document.fgColor = "white";

var myDemo = document.getElementById("demo");
console.log(myDemo);
myDemo.innerHTML = Date();
document.getElementById("demo").style.color = "red";
myDemo.style.fontStyle = "italic";
myDemo.style.textAlign = "center";

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM