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

jquery class starts with
jquery get element by class
jquery get class
jquery find elements that start with
get element by id starts with
jquery select multiple elements by class
jquery startswith
javascript get child element by class

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 
});

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/

Attribute Starts With Selector [name^=”value”], Description: Selects elements that have the specified attribute with a value Can be either a valid identifier or a quoted string. However it will be slower than using a class selector so leverage classes, if you can, to group like elements. How to find an element with a specific attribute (C#) 07/20/2015; 2 minutes to read +3; In this article. This topic shows how to find an element that has an attribute that has a specific value. Example. The example shows how to find the Address element that has a Type attribute with a value of "Billing".

You can also try:

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

Uses match instead of grep...

Selectors, Selects elements that have the specified attribute with a value beginning exactly with a given string. Also in: Selects all elements with the given class. Also in:  To find an element matching specific criteria in a given list, we: invoke stream () on the list. call the filter () method with a proper Predicate. call the findAny () construct which returns the first element that matches the filter predicate wrapped in an Optional if such an element exists.

 // Only select input which have class 
 $('input[class]').click(function(){  
   var myClass;
   // classNames will contain all applied classes
   var classNames = $(this).attr('class').split(/\s+/);  

     // iterate over all class  
     $.each(classNames, function(index, item) {
        // Find class that starts with btn-
        if(item.indexOf("btn-") == 0){
          // Store it
          myClass = item;
        }
     });

  });

Live Demo

Attribute selectors, The CSS attribute selector matches elements based on the presence or value of a given attribute. font-style: italic; } /* <a> elements whose class attribute contains the [attr*=value]: Represents elements with an attribute name of attr whose value contains at least one occurrence of value within the string. Write a Python program to find all words starting with 'a' or 'e' in a given string. Sample Solution:- Python Code: import re # Input. text = "The following example creates an ArrayList with a capacity of 50 elements. Four elements are then added to the ArrayList and the ArrayList is trimmed accordingly."

It would probably be better to store those values in the data attribute:

<input class="etape others" data-btntype="info">
<input class="etape others" data-btntype="inverse">
<input class="etape others" data-btntype="danger">

Then:

 $(".etape").click(function(){
     var myBtnType = $(this).data('btntype');
 });

jsFiddle

CSS [attribute^=value] Selector, on all <div> elements that have a class attribute value that begins with "test": matches every element whose attribute value begins with a specified value. Searching a character in the String. indexOf(char c): It searches the index of specified character within a given string.It starts searching from beginning to the end of the string (from left to right) and returns the corresponding index if found otherwise returns -1.

You could just make btn its own class. However, this will work.

$("div[class^='btn-']")

CSS Attribute Selector, It is possible to style HTML elements that have specific attributes or attribute to select elements with the specified attribute starting with the specified value. The following example selects all elements with a class attribute value that begins  The getElementsByClassName() method returns a collection of all elements in the document with the specified class name, as an HTMLCollection object. The HTMLCollection object represents a collection of nodes. The nodes can be accessed by index numbers. The index starts at 0.

Selectors, In CSS, pattern matching rules determine which style rules apply to elements in the document tree. "lang" attribute has a hyphen-separated list of values beginning (from the left) with "en". (In HTML, the same as DIV[class~="warning"​].) that match elements which have certain attributes defined in the source document. Beta. Gamma. Delta. Sigma. Use the split method against the string that needs to be divided and provide the separator as an argument. In this case, the separator is a comma (,) and the result of the split operation will give you an array split.

How To write good selectors, XPath can be less stable and potentially unsupported by certain ID, name, class, or anything else that is unique to the element The selector is saying 'find an input whose name contains the string It is used to start searching for an element anywhere in the DOM starting from the specified element. Get character in string Returns a reference to the character at position pos in the string . The function automatically checks whether pos is the valid position of a character in the string (i.e., whether pos is less than the string length ), throwing an out_of_range exception if it is not.

Use selector-syntax to find elements: jsoup Java HTML parser, You want to find or manipulate elements using a CSS or jquery-like selector syntax. Use the Element.select(String selector) and Elements.select(String selector) .class : find elements by class name, e.g. .masthead; [attribute] : elements with :matches(regex) : find elements whose text matches the specified regular  The element at ‘index’ in the given array is returned. Return Value: This method returns the element of the array as type of Object class. Exceptions: This method throws following exceptions: NullPointerException – when the array is null. IllegalArgumentException – when the given object array is not an Array.

Comments
  • what i want is th get the attribute class value when the element clicked
  • interesting i will try this
  • why match instead of grep?
  • It's the one that I know, just offering an alternative. Either way is good. Actually, this approach is slightly less complicated, you get the string directly without having to manipulate an array.
  • This won't work, the class attributes do not start with btn-.
  • @undefined: oops. Just got your point while making fiddle. Updated it again. Thanks!
  • Good, now it returns what it should. +1
  • this is a good idea , but my elements are generated dynamically , if there is simpler way ?
  • @fatiDev Since they're generated dynamically, why can't you set the data-btntype when creating the element?
  • what is meant is that the data btn type may be changed for the same button
  • I'm not sure I follow. You can change it with $(inputyouwantchanged).data('btntype', 'myNewButtonType').
  • what i want is to get attribute class which starts with btn for the element clicked