Search code examples
javascripthtmlfunctionstyling

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


Solution

  • 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>