2

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.

iSaumya
  • 1,503
  • 5
  • 21
  • 50
  • You should not have two elements with the same ID... – Patrick Moore Aug 24 '16 at 18:55
  • @PatrickMoore why? I thought it will make things easier to fetch via js also there are css for that id – iSaumya Aug 24 '16 at 18:55
  • I'd recommend a different approach, because as someone previously mentioned, having the same id for different elements will cause problems. – Henry Ollarves Aug 24 '16 at 18:57
  • @iSaumya Do you know what `id`s are? They are unique identification strings and you cannot have two elements with the same id. [The HTML5 specification prohibits repeated `id`s.](https://html.spec.whatwg.org/multipage/dom.html#the-id-attribute) – Derek 朕會功夫 Aug 24 '16 at 18:58
  • if I make them 1-someid, 2-someid still how do I get the values based on hover? – iSaumya Aug 24 '16 at 18:59

7 Answers7

2

Here is a way to do it based on your current configuration:

$('div').hover(function() {
        // grab class attribute, split on space character (like you're doing already)
        var class_names = $(this).attr('class').split( ' ' );

        // loop through each class
        $.each( class_names, function( k,v ){
            // see if this 1 class matches your example
            if ( v.indexOf("example-class") > 0 ){
                // if it does, remove text part of class name
                var this_num = v.replace( '-example-class', '' );
                // output numeric value only to console
                console.log( parseInt( this_num ) );
            }
        });

});

This method does not expect the same class configuration (meaning the classes in your class attribute can be in any order, so long as it does contain the example string). In your question, the code expects first class listed to be the example string class.

See this example: https://jsfiddle.net/31505tw1/

In the example, I have replaced your duplicate IDs into classes. As others have pointed out, HTML spec requires each ID to be unique.

Patrick Moore
  • 13,251
  • 5
  • 38
  • 63
  • if I make it 1-someid, 2-someid do you think it will be easier to fetch the numbers? – iSaumya Aug 24 '16 at 19:00
  • Take a look at the example here: https://jsfiddle.net/31505tw1/ you can do it all with classes (no IDs) – Patrick Moore Aug 24 '16 at 19:01
  • Hi Patrick, I've litle updated your code so that I can use the number using a global variable. But now it is not working and always showing 1. Check: https://jsfiddle.net/jbyt03vo/3/ Can you tell me how can I save the number so that I can use it globally? – iSaumya Aug 24 '16 at 20:13
  • @iSaumya you have the right idea already :) define outside of local scope, then use elsewhere. Try CLICK to see. https://jsfiddle.net/jbyt03vo/4/ – Patrick Moore Aug 24 '16 at 20:14
  • But whatif I don't wanna use the click function? I just wanna grab the value silently when people hover and then use the number elsewhere in my dynamic code. – iSaumya Aug 24 '16 at 20:17
  • @iSaumya the click event is just meant to illustrate using the number elsewhere. It's not related to hover event, it's just using that number that's defined on hover. So you can use elsewhere in your code, as long as your other code executes AFTER hover state. – Patrick Moore Aug 24 '16 at 20:26
2

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.

dNitro
  • 5,145
  • 2
  • 20
  • 45
  • The most easiest way to get the data. Thank you very much for the code. It works like a charm – iSaumya Aug 24 '16 at 19:26
  • why the following approach always is showing 1? http://pastebin.com/ieh7JgSqcan you take a look please? – iSaumya Aug 24 '16 at 20:00
  • because your console.log is outside callback function. move it inside. – dNitro Aug 24 '16 at 20:02
  • but I need that value in a global variable so that I can use it everywhere, Otherwise there is no pint of fetching the number. Please help – iSaumya Aug 24 '16 at 20:03
  • This is an asynchronous task. then you should write asynchronous code. – dNitro Aug 24 '16 at 20:06
1

There are several ways to do this- but other users are correct that your issue is in using the same ID multiple times, that's the only reason the code you already have doesn't work. If you use one of the other shared classes as your selector your original script will work:

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

    var class_name = class_names.split( ' ' ); 

    var c = parseInt( class_name[0] );

    console.log( c );
});
bl3d
  • 56
  • 4
0

Firstly, you should use unique ID's on your div's: https://stackoverflow.com/a/9454716/984323

Not only for the HTML to be valid, but your jQuery script wouldn't be able to differentiate between the two. Then you can target each div and the rest of your code seems to work.

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

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

https://jsfiddle.net/05r8f013/1

Community
  • 1
  • 1
mmmoustache
  • 2,273
  • 6
  • 41
  • 62
  • unfortunately `$('#someid, #someid2')` you have used, I cannot do that, I have to make it dynamic, as there will be endless ids like 1-someid, 2-someid, 3-someid and so on – iSaumya Aug 24 '16 at 19:02
0

Maybe you could for example:

$('div').hover(function(){
if ( $(this).attr('class') == 'some class' ) {
//Do something 
} else {
//Do something else...
}
Patrick Moore
  • 13,251
  • 5
  • 38
  • 63
Henry Ollarves
  • 509
  • 7
  • 18
  • Hey Henry unfortunately cant sompare it with some class as there will be endless classes like 1, 2, 3 .... the if else block will become endless to – iSaumya Aug 24 '16 at 19:06
  • If you could.explain better what exactly you are trying to achieve maybe I can come up with more elaborated solutions :) – Henry Ollarves Aug 24 '16 at 19:24
0

ID's must be unique all over html. Since you are using classname to get the data, you can add name field to the div:

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

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

 $('[name="someid"]').hover(function() {
    var class_names = $(this).attr('class');
    var class_name = class_names.split( ' ' ); 
    var c = parseInt( class_name[0] );
    console.log( c );
 });
v.coder
  • 1,822
  • 2
  • 15
  • 24
0

You could do a Regex on the hovered items that match on the pattern of the class name:

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



<script>

$('#someid').hover(function() {
   var className = this.className.match(/(\d)-example-class/);

   if(className){
      console.log(className[0]) // 1-example-classname
      console.log(className[1]) // 1
   }
});