iSaumya iSaumya - 11 months ago 44
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 id="2-someid" class="2-example-class border cz">
...more element goes here....

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
it will return me the class name
. and when people will hover on the div with
it will return me

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

Also please note that writing a static script for just
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 Source

Attribute selector and Regex is the way to go:

$("[class*=example-class]").hover(function() {
    var c = this.className.match(/(\d+)-example-class/)[1];
  • $("[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.