As I delve into the world of web development, I encountered a simple issue that has been causing me frustration for the past hour. It involves code to display the border color of a div
element using an alert
. The code works perfectly fine when the style is applied inline, but as soon as I move it to a style
element in the head section, it stops working.
Here's the working code:
function myFunction() {
alert(document.getElementById("myDiv").style.borderColor);
}
<div id="myDiv" style="border:thick solid green">This is a div.</div>
<br>
<button type="button" onclick="myFunction()">Return border color</button>
And now, the non-working code:
function myFunction() {
alert(document.getElementById("myDiv").style.borderColor);
}
<style>
#myDiv {
border: thick solid green;
}
</style>
<div id="myDiv">This is a div.</div>
<br>
<button type="button" onclick="myFunction()">Return border color</button>
I simply moved the style attribute from the div tag to the head section. Can anyone explain why this change caused it to stop working and guide me on how to fix it?