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

后端 未结 11 849
面向向阳花
面向向阳花 2021-02-03 21:19

I have a list of elements that have multiple classes, for example:


         


        
相关标签:
11条回答
  • 2021-02-03 21:27

    Try this,

    if($(selector).attr("class").lastIndexOf("classToStartFrom") == 0)
       return "this selector class name starts with 'classToStartFrom'";
    else
       return "this selector class name doesn't start with 'classToStartFrom'";
    

    The code is not tested.

    0 讨论(0)
  • 2021-02-03 21:31

    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/

    0 讨论(0)
  • 2021-02-03 21:32

    Try this: $('input[class*='btn']').attr("class");

    0 讨论(0)
  • 2021-02-03 21:32

    A class starting with btn and which can not be the first class:

    Working fiddle: http://jsfiddle.net/c9Tdx/

    $("input[class^='btn'],input[class*=' btn']").each(function(){
         //whatever
    });
    
    0 讨论(0)
  • 2021-02-03 21:34

    I just made @Vohuman 's function to reusable one :

    // getClassStartsWith(classes,startswith);
    // Example : getClassStartsWith( 'item w-2 h-4 hello' , 'h-' );
    function getClassStartsWith(t,n){var r=$.grep(t.split(" "),function(t,r){return 0===t.indexOf(n)}).join();return r||!1}
    

    Example...

    HTML :

    <div class="item w-2 h-4 hello"></div>
    

    JS :

    var $element = $('.item');
    var classes = $element[0].className;
    var getHeight = getClassStartsWith(classes,'h-');
    

    That will return h-4, And if no class starts with h- will return false

    Demo : http://jsbin.com/mijujunaca/edit?js,console

    0 讨论(0)
  • 2021-02-03 21:38
     // 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

    0 讨论(0)
提交回复
热议问题