0

How do I determinate if one of the buttons have the class "selected"?

<a id="foo">Foo</a>
<div id="div">
    <input type="button" />
    <input type="button" class="selected" />
    <input type="button" />
</div>

I wrap foo into a jQuery object. Call next() to get to the div. How do I do the rest?

function fooClickHandler(foo) {
    var $self = $(foo);
    var selectedExists = $self.next().children('input .selected');
};
BoltClock
  • 700,868
  • 160
  • 1,392
  • 1,356
radbyx
  • 9,352
  • 21
  • 84
  • 127

2 Answers2

3

Your selector is looking for a descendant of a input element with class selected which is not possible as input element cann't have children.

If you want to have a boolean value, you can use

var selectedExists = $self.next().children('input').hasClass('selected'); //or .is('.selected');
//here `selectedExists` will be a boolean value

If you want to have reference to the input element then

var selectedExists = $self.next().children('input.selected');
//here `selectedExists` will refer to the `input` element with class `selected` if there is one, else it will be empty jQuery object.
Arun P Johny
  • 384,651
  • 66
  • 527
  • 531
  • I can see in the doc. the is returns true/false. I have to check in javascript after on the value. Do you prefer next() or find() as robert commented on my question? – radbyx Feb 06 '15 at 09:23
  • I will use "hasClass" and not "is". But thanks for showing an alternative so I know about both. hasClass() vs is() benchmark: http://stackoverflow.com/questions/4901553/jquery-hasclass-vs-is – radbyx Feb 06 '15 at 09:45
1

use below code to check input have class 'selected'

var selectedExists = $self.next().children('input').hasClass('selected');

hasClass() return true if class assign to element

Nishit Maheta
  • 6,021
  • 3
  • 17
  • 32