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
var target_text = this.className.replace(/sfHover/, "");
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 ','');
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With