Reputation: 5957
I've a simple div
with various class attributs:
<div id="divId" class="anInformationIWantToGet aClassUsedForCss"></div>
I want to programatically get the anInformationIWantToGet
class which vary, the problem should be easy because others classes are known, so a Regex like following should do the job:
var anInformationIWantToGet = div.className.replace(/(\s*(aClassUsedForCss)?\s*)/, '');
But it doesn't work and I don't understant why... What did I miss?
I create a Fiddle to test the problem.
PS : my browser is Firefox17.
Upvotes: 1
Views: 713
Reputation: 13216
We will also change it by just adding class which we required and remove the remaining like that way.
$("#myDiv").attr("class","aClassUsedForCss");
Upvotes: 0
Reputation: 473
Be aware of replacing white spaces. Try this example.
var anInformationIWantToGet = div.className.replace(/(\s*(?:aClassUsedForCss)\s*)/, ' ').trim();
Upvotes: 0
Reputation: 2571
This will work
function replaceClass(){
/* Should not output 'hover' */
var reqdClasName = div.className.match(/(\S*)\s*hover\s*/)[1];
div.className.replace(reqdClasName, '');
result.innerHTML = reqdClasName;
}
Oops i had missed the replacing part. I ve updated
Upvotes: 0
Reputation: 943480
/(\s*(aClassUsedForCss)?\s*)/
^
You've made the class name you are looking for optional, so the first match will be the 0 or more white space at the beginning of the string.
Remove the ?
and/or make it a global regex (by appending g
).
Upvotes: 0
Reputation: 1796
Try this Change you below code
var anInformationIWantToGet = div.className.replace(/(\s*(aClassUsedForCss)?\s*)/, '');
To
var anInformationIWantToGet = div.className.replace(/(\s*(aClassUsedForCss)?\s*)/g, '');
put g in regular expression.
And working updated fiddle
Ask for more, If above is not working/Understood.
Upvotes: 1