Reputation: 67898
Is there a way to apply a class
by default to an element? Let's say for example I wanted to apply the class foo
to all input
elements:
.foo { ... }
My limited knowledge leads me to believe I need to mark that up every single time:
<input type='text' class='foo' />
<input type='password' class='foo' />
...
But, clearly I was hoping I could apply that class by default to all input
elements in the CSS somehow. I look forward to your answers!
In an attempt to clarify myself, I do not want to duplicate the CSS that already exists for foo
because I wouldn't want to have to change that in multiple places if I needed to change the style for foo
. Further, I will be applying it to more than just all input
elements.
Upvotes: 1
Views: 68
Reputation: 16325
You can add a class to elements easily using a framework like jQuery:
$(document).ready(function() {
$('input').addClass('foo');
});
EDIT: To address your latest update...
If you want to "extend" a class for only certain conditions, you can add a second class for that case... e.g.:
<input class="foo bar" />
<style type="text/css">
.foo.bar {
color: #123;
}
</style>
This will only apply your elements that are both .foo
and .bar
, and won't affect global .foo
styles, which will still be applied to all .foo
elements (including these)
Upvotes: 2
Reputation: 9774
You might try looking into a stylesheet preprocessor like LESS or SASS. These will allow you to use variables and other tricks here and there to help you avoid duplicating CSS. There are Javascript implementations of these as well as server-side ones if you would like to process it before giving it to the user.
Of course, the CSS ends up with duplicate code anyway, but you wouldn't have to write the same thing twice yourself.
For example, in LESS:
.foo {
color: #222222;
padding: 10px;
}
input {
.foo;
}
Upvotes: 1
Reputation: 723598
If you mean you want to take all the styles in your .foo
rule and apply them to input
s as well, just select both of them:
.foo, input { ... }
Upvotes: 2
Reputation: 1122
You could use javascript's document.getElementsByTagName(tag);
function.
Example:
var tags = document.getElementsByTagName("input");
for(i = 0;i<tags.length;i++){
tags[i].className = "foo";
}
If you want to keep the current classes on it just make sure to do if(tags[i].className != ""){tags[i].className = tags[i].className + " foo";}
. It'll carry over the current classes.
Upvotes: 1