Home > Software engineering >  why is my javascript style code not working
why is my javascript style code not working

Time:11-22

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

CodePudding user response:

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?

CodePudding user response:

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";
}

CodePudding user response:

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>
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

  • Related