jquery hasClass, can it be given the beginning of class name, to get the full class name
javascript, jquery
Solution
Description
You can use jQuerys `Attribute Contains Selector`, `.attr()` and `.click()` method.
Attribute Contains Selector - Selects elements that have the specified attribute with a value containing the a given substring.
.attr() - Get the value of an attribute for the first element in the set of matched elements.
.click() - Bind an event handler to the "click" JavaScript event, or trigger that event on an element.
Sample
html
<span class="anyclass test-hello">Hello World</span>
jQuery
$("[class*='test']").click(function() {
var object = $(this);
alert(object.attr("class").match(/(test-.*?)(?:\s+|$)/)[1])
;});
Check out the updated jsFiddle
Update
If you dont want to use regex you can do this.
$("[class*='test']").click(function() {
var object = $(this);
alert("test-" + object.attr("class").split("test-")[1].split("-"))
;});
More Information
- jQuery - Attribute Contains Selector
- jQuery - .attr()
- jQuery - .click()
- jsFiddle Demonstration
Problem
I'm trying to do something similar to this question, but it's a bit different, so the solution there isn't working for me. ``` <span class="a-class another-class test-top-left"></span> ``` I have an element (this code shows a `span` but it could be `div` `span` or anything). This element has a class beginning with `test-` (`test-top-left`, `test-top-right` etc.) I've triggered a click event on classes starting with `test-` and saved the clicked object as `var object = this;`. Simple stuff so far. What I'm trying to do now is get the full name of that class (`test-top-left`). I know it starts with `test-` but what's the full name. The thing is that there are other classes `a-class` `another-class` and `test-top-left`. Can `hasClass` be used to get the full name of the class? I'd prefer not to use `find()` or `filter()` just because there may be additional elements within that also have `class="test-"` Edit: The code I have now is, but it gives me ALL the classes. What I need is the single class beginning with `test-`. ``` var object = this; $(object).attr('class'); ``` So now I for loop through all the classes and test each one separately, which seems like a lot of unnecessary code. I'm hoping jQuery has a clever way to get the exact class that was clicked right away.