How to Style an Element using Javascript

0 min read 107 words

If you need to style an element using Javascript then you can use the style object to support all your CSS needs.

<html>
  <body>

    <p id="p1">Hello World!</p>

    <script>
      document.getElementById("p1").style.color = "red";
    </script>

    <p>The paragraph above was changed by a script.</p>

  </body>
</html>

If you need to do this purely in a Javascript file itself, then:

// Get a reference to the element
var myElement = document.querySelector("#p1");

// Now you can update the CSS attributes
myElement.style.color = "red";
myElement.style.backgroundColor = "yellow";

Note that where CSS properties would use dashes to separate words, like background-color, Javascript instead uses camel casing and drops the space.

Example: background-color would become backgroundColor.

Andrew
Andrew

Andrew is a visionary software engineer and DevOps expert with a proven track record of delivering cutting-edge solutions that drive innovation at Ataiva.com. As a leader on numerous high-profile projects, Andrew brings his exceptional technical expertise and collaborative leadership skills to the table, fostering a culture of agility and excellence within the team. With a passion for architecting scalable systems, automating workflows, and empowering teams, Andrew is a sought-after authority in the field of software development and DevOps.

Tags