For example:
<div class="home current">home</div>
When I use $(this).attr("class")
, it simply returns "home current".
I want to get the "home" attribute only. How can I achieve this?
For example:
<div class="home current">home</div>
When I use $(this).attr("class")
, it simply returns "home current".
I want to get the "home" attribute only. How can I achieve this?
If you know the class name and want to check if an element has it, you can use .hasClass()
// will return true if the element has that class applied to it
$(elem).hasClass('home');
On the other hand, if you want each class applied to an element separately, you can split by space and iterate:
var classes = $(elem).attr('class').split(' ');
for(var i=0; i<classes.length; i++) {
classes[i]; // each class name
}
The class
attribute returns the space delimitered list of css classes assigned to the element, to convert this into an array use the split
method on the string, and to retrieve the first one, use the [0] indexer, as in:
var firstClass = $(this).attr('class').split(' ')[0]
var allClass= $(this).attr("class");
var class = allClass.replace("current", "");
this will work if you only have "current" as an additional class
Is there a specific reason that you need to pull the class list. If you know the class you are looking for and just need to check if the object has the class home, you could do this:
$(this).hasClass("home");
Otherwise, you could just split the result and check for whatever class you need.
var classAttr = $(this).attr("class");
var classes = classAttr.split(" ");
It seems you need the primary class of the element.
var primaryClass= $(this).attr('class').split(' ')[0].
Remember this line may cause exception if no class applied,while the time you using it.