JavaScript text color modification not working

Hey everyone!

I’m just starting out with JavaScript and I’m having trouble getting my code to work properly. I wrote a simple function that should turn some text red when I click a button, but nothing happens when I press it.

I think there might be something wrong with how I’m selecting the element or changing its style properties. Could someone take a look at my code and help me figure out what I’m doing wrong?

<!DOCTYPE html>
<html>
<head>
<script>
function changeTextColor()
{
var textElement = document.getElementById("myText").innerHTML;
textElement.style.color = "red";
}
</script>
</head>
<body>

<h1>Learning JavaScript Colors</h1>
<p id="myText">Press the button below to change color...</p>

<button onclick="changeTextColor()">Change Color</button>

</body>
</html>

Any help would be really appreciated. Thanks!

You’re running into this because innerHTML grabs the text as a string, not the actual DOM element. When you use document.getElementById(“myText”).innerHTML, you just get “Press the button below to change color…” - which you can’t style. Change that line to var textElement = document.getElementById(“myText”); and you’ll get the actual paragraph element that you can modify. I made the same mistake when I started - it’s easy to think innerHTML gives you the element itself.

i totally feel ya! just change that line to get the element itself, not the innerHTML. use var textElement = document.getElementById("myText"); then textElement.style.color = "red";. super common mistake, you’ll nail it!

The problem’s right here: var textElement = document.getElementById("myText").innerHTML; - you’re getting the innerHTML instead of the element itself. When you use .innerHTML, you just get a string of the text content, and strings don’t have style properties. Just change it to: var textElement = document.getElementById("myText"); and drop the .innerHTML part. Then textElement.style.color = "red"; will work since you’ll actually have the DOM element with style properties. I made this same mistake learning JavaScript - super common beginner error but easy fix once you get the difference between grabbing the element vs its content.