Changing CSS properties from JavaScript

JavaScript

0 Comments

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');

firstParagraph.style.fontWeight = '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
firstParagraph.style.textDecoration = 'underline';

// Change the CSS padding-left property
firstParagraph.style.paddingLeft = '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.

Example

HTML

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

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

JavaScript

Open Editor

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

    myButton.addEventListener('click', hideParagraph);
}

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

    hideMe.style.display = 'none';
}

setupButton();

Leave a Comment