Antonio Ivanov
Antonio Ivanov

Reputation: 13

why is my javascript style code not working

here is my html code:

<body>
<p id="text">Change my style</p>
<div>
    <button id="jsstyles" onclick="style()">Style</button>
</div>
</body>

here is my javascript:

function style()
{
Text.style.fontSize = "14pt";
Text.style.fontFamily = "Comic Sans MS";
Text.style.color = "red";
}

I dont see a problem in this code and its still not working

Upvotes: 0

Views: 1170

Answers (3)

Reyhan Farabi
Reyhan Farabi

Reputation: 34

There is a few problem in your code

  1. You need to set variable to what element you want to change in your javascript.
  2. You can't name your function style() because the name style is already use in javascript. Instead try different name like handleStyle() or something else.

// Set variable to what element you want to change
const Text = document.querySelector("#text");

// For this example I use handleStyle for the function
function handleStyle() {
  Text.style.fontSize = "14pt";
  Text.style.fontFamily = "Comic Sans MS";
  Text.style.color = "red";
}
<body>
    <p id="text">Change my style</p>
    <div>
        <button id="jsstyles" onclick="handleStyle()">Style</button>
    </div>
</body>

Upvotes: 0

Shawn
Shawn

Reputation: 132

As Barmer mentioned in the comment, you don't set the variable.

More important, you can't use style as a variable or function name. I tried to use style as a funtion name and it produced error where style is not a function

This should work:

<body>
<p id="text">Change my style</p>
<div>
    <button id="jsstyles" onclick="styles()">Style</button>
</div>
</body>
var Text = document.getElementById('text')
function styles()
{
Text.style.fontSize = "14pt";
Text.style.fontFamily = "Comic Sans MS";
Text.style.color = "red";
}

Upvotes: 0

nlta
nlta

Reputation: 1914

It should be text not Text.

Or even better use document.getElementById.

Using named access on the window object is frowned upon. Do DOM tree elements with ids become global variables?

Upvotes: 1

Related Questions