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

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

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


         


        
11条回答
  •  谎友^
    谎友^ (楼主)
    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 :

    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

提交回复
热议问题