0

So let's I have a div with multiple classes like this:

<div class="s1 s"></div>

In the javascript I only want the first class, like

$(document.body).on('click','.s',function(){
   var firstClass = //only get s1 from that one whole class.
});

How can I do this?

Code Lღver
  • 15,573
  • 16
  • 56
  • 75
southpaw93
  • 1,891
  • 5
  • 22
  • 39
  • This is a bad idea. The DOM does not have a concept of a "first" class, all class names on an element are treated equally. If you do this then your code will work against the expectations of pretty much every other developer and will attract bugs. What's the real problem you are trying to solve? – Jon Dec 16 '13 at 12:58
  • @Jon Yep, sounds like another classic case of the XY problem. This seems like an entirely terrible idea. – sbking Dec 16 '13 at 13:00
  • Just out of curiosity: Why do you want to do this? – putvande Dec 16 '13 at 13:02
  • inside of that `div` I have another `div class='s1_info'` and I only need the 's1' string so I can form `s1_info` so I can append something to the new formed class. – southpaw93 Dec 16 '13 at 13:04

2 Answers2

3

Try this:

$('.s').click(function()
{ 
  var firstClass = $(this).attr('class').split(" ")[0];
});
Ringo
  • 3,795
  • 3
  • 22
  • 37
1

Try This:

var firstClass = this.className.split(" ")[0];

No need to wrap it back into a jQuery element and incur the performance cost.

Breno Gazzola
  • 2,092
  • 1
  • 16
  • 36