iSaumya iSaumya - 3 months ago 9
CSS Question

How to get a class name based on div hover in jquery

I'm looking for a way to fetch the class name based on hovering on a div. Both div has same id but slightly different class name. take a look at the below example:

<div id="1-someid" class="1-example-class border cz">
...more element goes here....
</div>


and

<div id="2-someid" class="2-example-class border cz">
...more element goes here....
</div>


Update: I've made the id name unique based on expert's opinion posted below. :) Thanks for all the helps.

Now what I want is, when user hover on the div with
1-example-class
it will return me the class name
1-example-class
. and when people will hover on the div with
2-example-class
it will return me
2-example-class
name.

So that I can use
parseInt()
on that name to fetch the number, 1, 2, 3 and so on.

Also please note that writing a static script for just
1-example-class
or
2-example-class
will not help as there are many more divs like this with 3, 4, 5 and so on attached to it.

Can anyone help? I have tried the following but it didn't helped.

$('#someid').hover(function() {
var class_names = $(this).attr('class');

var class_name = class_names.split( ' ' );

var c = parseInt( class_name[0] );

console.log( c );
});


If anyone can help it will be really helpful.

Answer

Attribute selector and Regex is the way to go:

$("[class*=example-class]").hover(function() {
    var c = this.className.match(/(\d+)-example-class/)[1];
    console.log(c);
});
  • $("[class*=example-class]") matches all elements that their class attribute includes 'example-class' string.

  • this.className.match(/(\d+)-example-class/)[1] gives the related number.