0

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

  • Where do you set the variable `Text`? – Barmar Nov 21 '21 at 21:51
  • 1
    Are you getting any errors in the console? – Barmar Nov 21 '21 at 21:52
  • What do you mean "not working"? Not invoked or throws and error or not updating text field (because of typo)? How is your Javascript wired into HTML? You might find reading the site [help] useful when it comes to [ask], and this question [checklist](https://meta.stackoverflow.com/questions/260648/stack-overflow-question-checklist). – Felix Nov 21 '21 at 21:58

3 Answers3

1

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?

nlta
  • 1,716
  • 1
  • 7
  • 17
0

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";
}
Dharman
  • 30,962
  • 25
  • 85
  • 135
Shawn
  • 132
  • 1
  • 1
  • 13
0

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>
  • Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Nov 22 '21 at 01:55