Dave
Dave

Reputation: 19150

How do I use JQuery to select an item that is currently being hovered over?

I’m using jQuery 1.12. I have the following class, which applies to items that have the mouse hovered over them

.select-options li:hover {
  color: gray;
  background: #fff;
}

I would like to use jQuery to select the item that currently has the hover (the above class), so I tried

elt = $('.select-options li:hover')

But this isn’t working, at least, it isn’t in my Fiddle — http://jsfiddle.net/cwzjL2uw/11/ . Open up one of the Select drop downs, hover over one of the items, and then press any key on the keyboard to activate my selector. The selector repeatedly returns “undefined”.

Upvotes: 2

Views: 55

Answers (2)

charlietfl
charlietfl

Reputation: 171669

A jQuery object has no outerHTML property...the underlying dom elements do

Try changing

$(window).keydown(function(event){
    elt = $('.select-options li:hover')
    console.log(elt.outerHTML); 
});

To

$(window).keydown(function(event){
    elt = $('.select-options li:hover')
    console.log(elt[0].outerHTML);    
});

you will need to add additional checks to see if elt actually has matches also or will run into errors

Upvotes: 1

D. Foley
D. Foley

Reputation: 1024

Depends on what data you want, but you are logging the wrong thing.

Change your console.log to:

console.log(elt[0].innerHTML);

and you will get textual data of whatever you are hovering over.

Upvotes: 0

Related Questions