Changing CSS properties from JavaScript



CSS properties can easily be changed through JavaScript, which means you can easily hide or show hidden elements on the page.

For example, the following code makes the first paragraph bold.

var firstParagraph = document.querySelector('p'); = 'bold';

With CSS, you'd normally use the font-weight property to make something bold. However, JavaScript uses a slightly different syntax for accessing CSS properties. Instead of font-weight you use fontWeight, and this is basically how it works for all the CSS properties. You capitalize any letters that have a dash (-) before them and then remove all the dashes (this is called camel casing). See the code below for a few more examples.

// Change the CSS text-decoration property = 'underline';

// Change the CSS padding-left property = '10px';

Practice Problem - Hiding things with JavaScript

Write the JavaScript code to hide the paragraph with class="hideMe" when the button is pressed. An example of how this should work is included below along with the HTML code.



<input type="button" id="myButton" value="Click me">

<p class="hideMe">
    This paragraph is about to be hidden.


Open Editor

function setupButton() {
    var myButton = document.querySelector('#myButton');

    myButton.addEventListener('click', hideParagraph);

function hideParagraph() {
    var hideMe = document.querySelector('p.hideMe'); = 'none';


Leave a Comment