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

I need to get the element class. Another plugin inserts a second class into an element, but I don't want to get this second class. So far I:

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

What is currently returning:

 some-class sfHover 

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

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

thanks

+7
source share
4 answers
 var target_text = this.className.replace(/sfHover/, ""); 
+2
source

Like 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 ',''); 
+2
source

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

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

No need to use jQuery methods when you are doing simple DOM things.

Note that the above will be an error if the element has class NO (I think className will be null). It may 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 reorganize your code so as not to save state in the DOM. Try to avoid storing information in the DOM, it's expensive, and the DOM is ugly.

0
source

If you want the first class to try: $(this).attr("class").get(0)

-one
source

All Articles