Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get only one particular class using $(this).attr("class") instead of multiple classes

Tags:

jquery

css

class

I need to receive the class of an element. Another plugin inserts a second class to the element but I do not want to receive this second class. So far I have:

target_text = $(this).attr("class");

Which returns at the moment:

some-class sfHover

I do not want to get the class "sfHover". How can I remove it from my variable?

(The classes I want to get are generated dynamically, so I cannot listen for specific names and only use those.)

Thanks

like image 497
maze Avatar asked Jul 02 '11 12:07

maze


3 Answers

var target_text = this.className.replace(/sfHover/, "");
like image 88
Tomalak Avatar answered Oct 16 '22 12:10

Tomalak


Similar to Tomalak's answer:

Your jQuery statement returns a string (the jQuery attr() method returns a string), so you should manipulate it with simple javascript:

target_text = $(this).attr("class").replace('sfHover ','');
like image 2
alex Avatar answered Oct 16 '22 11:10

alex


If you always know your class will be first, and you always know it will have a class:

target_text = this.className.split(' ')[0]

No need for jQuery methods when you are doing simple DOM stuff.

Note the above will error if the item has NO class (I think, className would be null). Might be safer to do

target_text = this.className && this.className.split(' ')[0]

Also, depending on what you are trying to do, you may want to consider refactoring your code to not store state in the DOM. Try to avoid storing information in the DOM, it's expensive and the DOM is ugly.

like image 1
Andy Ray Avatar answered Oct 16 '22 11:10

Andy Ray