Reputation: 93
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.
Upvotes: 4
Views: 354
Reputation: 262939
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
.
Upvotes: 1
Reputation: 1399
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/
Upvotes: 0
Reputation: 348992
/\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.
Upvotes: 1