Celeritas
Celeritas

Reputation: 15091

Changing CSS with JavaScript

When using JavaScript to change the CSS does the JavaScript simply make new inline-CSS which takes presidents? I've always felt inline CSS is trashy and was wondering if there's a better way?

For example if you have

<div id="author">Author's name</div> which is normally coloured green from a reference to an external CSS and you want to change it to red must you use

document.getElementById('author').style.color='#FF0000'

Must changes to appearance be done using inline-stying?

Upvotes: 0

Views: 180

Answers (3)

Islam El-Khayat
Islam El-Khayat

Reputation: 416

It is always cleaner to define all your styles in classes so you can change the whole application look and feel easily instead of using inline styles.

the easiest way to do so is to define a CSS class

.reddiv {color: #FF0000}

then you can easily change the color of the div to red using jquery

$('#author').addClass('reddiv');

Upvotes: 0

BinaryTox1n
BinaryTox1n

Reputation: 3566

There is more than one way to change the styling of an HTML element. If using jQuery, for instance, you can add/remove class names to elements easily, like so:

$("div").addClass("className");

Upvotes: 0

Halcyon
Halcyon

Reputation: 57723

No, you're not modifiying the CSS. You're just setting style properties. The mark up of an element is decided by three things: CSS, style and inline properties like width="100". The order in which they are applied can get a little fuzzy.

style does always overrule CSS though, unless you're using !important.

A more common way to change the mark up of elements is to add and remove classes. This allows you to keep all your style definitions in your CSS file and makes your code considerably less complex.

You could do:

document.getElementById('author').className = "selected";

to add a class to it and have it be display in a different mark up.

If you're using jQuery you can use addClass and removeClass. Under the hood this just modifies the className property. It's easy enough to write your own implementation, you just need to do some string juggling.

Upvotes: 2

Related Questions