I have a list of elements that have multiple classes, for example:
<input class="etape btn-info others"> <input class="etape btn-inverse others"> <input class="etape btn-danger others">
How to write jQuery-code that will allow me the following...
$(".etape").click(function(){ $(this).get("the class that starts with btn-") // in order to store this value in a variable to reuse it later });
If you want only the first element in the DOM with that class, you can select the first element out of the array returned. var elements = document. getElementsByClassName('className'); var requiredElement = elements[0];
Use the getElementsByClassName method to get elements by multiple class names, e.g. document. getElementsByClassName('box green') . The method returns an array-like object containing all the elements that have all of the given class names.
You can use Regular Expression or split
the class name.
$(".etape").click(function(){ var classes = $.grep(this.className.split(" "), function(v, i){ return v.indexOf('btn') === 0; }).join(); });
http://jsfiddle.net/LQPh6/
You can also try:
$(".etape").click(function () { var theClass = $(this).attr("class").match(/btn[\w-]*\b/); console.log(theClass); });
Uses match instead of grep...
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