Reputation: 11260
I have a selector that selects multiple elements. I want to check if at least one of these elements has the focus.
By experimenting, I noticed that .is(":focus")
and .has(":focus")
didn't work when dealing with multiple elements, see below:
console.log( $('.text-block').is(":focus") ); // prints false
console.log( $('.text-block').has(":focus") ); // prints empty object array
console.log( $('.text-block').filter(":focus") ); // prints empty object array
console.log( $('.text-block:focus') ); // prints one element (works!)
as :focus
selector seems the only way to go, my question is: how to do if my elements ($('.text-block')
) are in a variable (like $myElements
) ?
(Second question would be to understand why only :focus
selector works for me.)
Upvotes: 0
Views: 1547
Reputation: 3559
Try this:
$('text').each(function() {
if ($(this).is(':focus')) {
console.log('This element has focus!');
}
});
Upvotes: 0
Reputation: 3016
Loop through each element and test if has :focus
.
$('.text-block').each(function() {
if ($(this).is(':focus')) {
console.log('This element has focus!');
}
});
I tested this with some basic HTML inputs and it works: http://jsbin.com/aTaqagOz/1/ (the JSBin I worked on was working but the preview appears not to)
Maybe your elements aren't focusing correctly?
Upvotes: 1
Reputation: 3061
as you can read here http://api.jquery.com/focus-selector/ is(":focus")
is the way to go. if it returns false that means it does not have the focus.
you can also get he focused element by $( document.activeElement )
.
as it stated in the jquery doc it supported starting with version 1.6 I know it is a long shot but may be you have an older version.
Upvotes: 0