Navin Rauniyar
Navin Rauniyar

Reputation: 10525

select current class with jquery

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

Answers (2)

blgt
blgt

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

Arun P Johny
Arun P Johny

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

Related Questions