...

View Full Version : Convenient change class



questionable
01-24-2012, 04:32 AM
Hello,

Let's say I have a <div class="main1 secondary">.

Is there an easy way to change "main1" to "main2" and make sure it is the first class?

I was thinking about using jquery with .removeClass and .addClass but addClass adds it to the end.

Any help would be great!

Thanks

Old Pedant
01-24-2012, 04:39 AM
Hmmm...maybe you could just do:


var obj = document.getElemenetById("someID");
obj.className = obj.className.replace( /main1/, "main2" );

???

Untested. But easy to try.

Logic Ali
01-24-2012, 05:08 AM
Hello,

Let's say I have a <div class="main1 secondary">.

Is there an easy way to change "main1" to "main2" and make sure it is the first class?
Where myDiv is a reference to the element:


myDiv.className = "main2 " + myDiv.className.replace( /\bmain1\b/g, '' );

Old Pedant
01-24-2012, 08:46 AM
Yeah, that's a better way...makes sure that main2 is first class mentioned.

Dormilich
01-24-2012, 08:48 AM
Hello,
I was thinking about using jquery with .removeClass and .addClass but addClass adds it to the end.

why does that matter?

VIPStephan
01-24-2012, 11:20 AM
Is there an easy way to change "main1" to "main2" and make sure it is the first class?

Replacing a class with jQuery is easy with toggleClass() but the order of the classes is of no relevance whatsoever. And if thatís the only thing you wanna do, using jQuery is the worst way because it adds a lot of overhead (much code to parse) for such a simple thing.

mrhoo
01-24-2012, 03:55 PM
As others have mentioned, the precedence of the classes depends on the order they are defined in the style sheets,
not the order they are listed in the class atribute.


<!doctype html>
<html lang="en">
<head>
<style>
body{font-size:125%;margin:1ex 2em;}
.noborderClass{border:none}
.borderClass{border:solid 1px black;}
.maybeNoBorder{border:none}
</style>
<meta charset= "utf-8">
<title>Small Page</title>
</head>
<body>
<h1>Small Page</h1>
<pre>
&lt;style>
.noborderclass{border:none}
.borderclass{border:solid 1px black;}
.maybeNoBorder{border:none}
&lt;/style>
</pre>
<p class="borderClass noborderClass">
class="borderclass noborderclass"<br>
Since noborderclass is defined <strong>before</strong>
borderclass, the rules defined in
borderclass are the last ones applied.</p>
<p class="maybeNoBorder borderClass">
class="maybeNoBorder borderclass"<br>
maybeNoBorder is <strong>defined</strong>
last, it doesn't matter what order it is in the class attribute.
</p>
</body>
</html>

Logic Ali
01-24-2012, 04:51 PM
the order of the classes is of no relevance whatsoever.I just assumed it was OCD (http://www.medicinenet.com/obsessive_compulsive_disorder_ocd/article.htm).

questionable
01-25-2012, 04:06 AM
Thanks!



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum