4

I have a div with two class.

<div class="one two"></div>

I need to get first of them without .split() callback.

$(this).parent('div[class]').attr('class').split(' ')[0]

Any idea?

Thanks in advance.

UPD: Why I need this? ) Because then I use split(), code inspector in Chrome said exactly :

Uncaught TypeError: Cannot call method 'split' of undefined

аnd some function not work properly.

Nixon
  • 83
  • 1
  • 9
  • 5
    What wrong with `split()`? What don't you want to use it? – Frédéric Hamidi Jan 18 '12 at 10:48
  • What's wrong with using .split() ? – Didier Ghys Jan 18 '12 at 10:48
  • http://stackoverflow.com/questions/3203966/jquery-get-the-first-class-only-from-a-element The value of class is a single string regardless of how many individual class names make up the string. I can't think of a way to do it *without* split()! But yeah, what is the problem with split()..? – danwellman Jan 18 '12 at 10:52
  • **Frederic, Didier** - when I use `split()` with my js, some functions are not work properly, and code inspector sad that `Cannot call method 'Split' of undefined ` – Nixon Jan 18 '12 at 10:58
  • 1
    @Nixon that is a different problem entirely – J. Holmes Jan 18 '12 at 11:01
  • 1
    @Nixon - If you've copied that error message exactly your problem was that you were trying to call `Split` rather than `split`. Note the lower-case `s`. – James Allardice Jan 18 '12 at 11:02
  • @Nixon. the proper method is called `split` (in lowercase). More generally, javascript function names are camelCase. – Didier Ghys Jan 18 '12 at 11:06
  • Is that error saying split is undefined or can't call split *on* undefined? – J. Holmes Jan 18 '12 at 11:08
  • **32bitkid, James Allardice** i've updated post and write what said exactly code inspector. And **split** write with lower-case **s** – Nixon Jan 18 '12 at 11:20

3 Answers3

1

/\S*/.exec(this.parentNode.className)[0]; will give the first class of the parent class, if any.

This method is more efficient than your current method: Your method returns an empty string when the class attribute starts with a space.

Rob W
  • 341,306
  • 83
  • 791
  • 678
  • As a response to the updated question, ensure that `this` points to a child of your `
    `. *If `this` is not a direct child, you might want to use [`.closest('div[class]')`](http://api.jquery.com/closest/).
    – Rob W Jan 18 '12 at 11:14
1

If you're really adverse to using split(), you can combine indexOf() and substr():

var classes = $(this).parent("div[class]").attr("class");
var firstClass = classes.substr(0, classes.indexOf(" "));

However, the code above will only work if there are more than one class name in classes.

Frédéric Hamidi
  • 258,201
  • 41
  • 486
  • 479
0

I dont know what you are trying to do with the info but if you are checking if he has one as class just try it like this. I used a button since I needed a child to trigger the event ;) http://jsfiddle.net/c3VdH/

Teun Pronk
  • 1,367
  • 12
  • 24