Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get elements of specific class starting with a given string?

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  }); 
like image 621
fatiDev Avatar asked Mar 19 '13 16:03

fatiDev


People also ask

How do I find the first element of a class name?

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];

How do you find an element with multiple classes?

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.


2 Answers

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/

like image 140
undefined Avatar answered Sep 19 '22 18:09

undefined


You can also try:

$(".etape").click(function () {     var theClass = $(this).attr("class").match(/btn[\w-]*\b/);     console.log(theClass);  }); 

Uses match instead of grep...

like image 45
Marc Audet Avatar answered Sep 19 '22 18:09

Marc Audet