1

I'm trying to get the name of a class that matched a regex of a checked input.

If I have this:

 <input type="radio" class="toggle toggle-1" />
 <input type="radio" class="toggle toggle-2" checked="checked" />
 <input type="radio" class="toggle toggle-3" />

I want to find out that 'toggle-2' is the checked class.

 $('.toggle:checked').className.match(/toggle\-.+?\b/);

But that produced 'className is undefined' errors.

I think my problem is that I'm using className against a jQuery object. But I'm not really sure what the alternative is.

DA.
  • 39,848
  • 49
  • 150
  • 213

4 Answers4

9

You can call the attr method to get any underlying attributes on the element you need.

$('.toggle:checked').attr('class').match(/toggle\-.+?\b/); 
Shawn
  • 19,465
  • 20
  • 98
  • 152
6

className is a standard DOM member, not a jQuery wrapper property. Either access through $('something')[0].className or jQuery $('something').attr('class'), but you can't mix them.

You appear to have multiple radio​s without a shared name? That won't work, they'll all act ast separately checkable fields. All radio controls that belong together need to have the same name (but different value​s) and be placed within the same form.

bobince
  • 528,062
  • 107
  • 651
  • 834
  • Nice explanation, bobince. Thanks! As for the markup, it was just for example. I omitted a bunch of attributes. – DA. Dec 18 '09 at 01:58
  • odd then it is that I've had this working since v1.4.4: var className=$("#myTBody").attr("className"); It only failed when I upgraded to v1.7.1 – KalenGi May 22 '12 at 05:42
  • @kalengi: that would be due to the infamous [`attr`/`prop` split](http://stackoverflow.com/questions/5874652/prop-vs-attr) where jQuery tried to do the right thing (and ended up breaking everything). – bobince May 22 '12 at 06:03
0

Don't you need an Id on all items jQuery is to look at?

Martin
  • 9
  • 1
  • 1
    No, jQuery can select elements based on pretty much any attribute using a wide variety of selectors. – Annabelle Dec 17 '09 at 23:23
  • 1
    Not at all. You can use any CSS selector (in addition to tons of other options) to locate elements in the DOM with jQuery. – Mark Hurd Dec 17 '09 at 23:23
0
$('.toggle:checked').hasClass('toggle-2');
Corey Hart
  • 10,316
  • 9
  • 41
  • 47