Reputation: 10525
Suppose I have the following html:
<div class="nav-1 anotherClass">menu one</div>
<div class="someClass nav-2">menu two</div>
Now, I would like to select the class like this:
var nav = $('[class^=nav]').attr('class').split(' ')[0];
It gets nav-1 for first div and someClass for second div.
How can I get the class which starts with nav?
I tried this but not worked:
var nav = $('[class^=nav]').attr('class').split(' ')[this];
Is there any around simple?
Upvotes: 0
Views: 385
Reputation: 8205
No, unfortunately there's no simple way of getting at a particular class. You have to loop through all classes:
var navList = $('[class*=nav]').attr('class').split(' ');
var nav;
for(var i in navList) {
if(navList[i].indexOf('nav') === 0) { nav = navList[i]; break; }
}
That's why it's common to use custom html attributes, e.g.
<div class="nav anotherClass" data-custom-value=1>menu one</div>
<div class="someClass nav" data-custom-value=2>menu two</div>
And...
var navNumber = $('.nav').attr('data-custom-value');
Upvotes: 1
Reputation: 388316
Try
var nav = $('[class|=nav]').attr('class').match(/(nav-[^\s]+)/)[0];
or
$('[class|=nav]').each(function(){
var nav = this.className.match(/(nav-[^\s]+)/)[0]
})
Upvotes: 1