santa
santa

Reputation: 12512

Dynamically assign CSS class to another class

Is it possible to assign properties of one CSS class to another class? If it can not be done with CSS, I can use server-side scripting to pass variables.

For example, if I have a list of classes from .myclass1 to .myclass20 and I know that for user7 I need to replace .myDefault with myClass7, how can I do that?

Upvotes: 0

Views: 682

Answers (5)

alex
alex

Reputation: 5002

You can use PHP to handle this for you. Just replace e.g.

<div class='myDefault'></div>

with

// you should have that info stored somewhere anyway :)
$userClass = 'myClass7';

// now just echo out the right class for the user
<div class="<?php echo $userClass ?>"></div>

Upvotes: 0

imsky
imsky

Reputation: 3279

Here's a simple way to swap classes without jQuery: http://jsfiddle.net/imsky/mrKHB/

HTML:

<div id="test" class="big one sans phone">Hello world and </div>

CSS:

.one {background:blue;color:#fff}
.two {background:yellow;color:#000}
.sans {font-family:sans-serif}
.big {font-size:24px}
.phone:after {content:"phone!"}

JavaScript:

document.getElementById("test").onclick = (function(){
this.className = this.className.replace(/\bone\b/,"two");
});

Upvotes: 0

Mihai Stancu
Mihai Stancu

Reputation: 16107

You want all properties in a class to be inherited by another class in CSS.

Not for both classes to be applied on an object dynamically by JS.

That can't be done directly with CSS and a JS approach would consume quite a bit of time for you to implement.

Best choice is for you to look into less css.

It does what you want, either server side or clientside.

Upvotes: 1

scunliffe
scunliffe

Reputation: 63580

This isn't a direct answer, but if you want a mix of settings you can use multiple classes:

bigFont{
  font-size:150%;
}
errorBox{
  border:4px dashed red;
}
typMessage{
  padding:2px;
  margin:1px;
  overflow-y:auto;
}


<div class="typMessage">Hello World</div>

by adding the "errorBox" and/or "bigFont" class to the element it will "merge" the CSS properties.

Upvotes: 0

Kenny Thompson
Kenny Thompson

Reputation: 1492

In jQuery you could this code:

$('.myDefault').addClass('myClass7');
$('.myClass7').removeClass('myDefault');

Upvotes: 1

Related Questions