jQuery - How to select value by attribute name starts with

后端 未结 4 1923
春和景丽
春和景丽 2020-11-28 15:08

I want to select attribute value by giving attribute name (only starts with) For instance if we have html tag

4条回答
  •  眼角桃花
    2020-11-28 15:35

    If you want all data-* attributes, you can iterate through jq data object:

    $('.slide').each(function(){
        for(data in $(this).data())
            console.log(data); // returns confirmID so element as an attribute `data-confirmID`
    });
    

    But this data object can contains other keys which aren't attribute, setted for example by some plugins.

    EDIT

    To get all kinds of attribute to "starts with", you can customize your own jQuery selector:

    jQuery.extend(jQuery.expr[':'], {
        attrStartsWith: function (el, _, b) {
            for (var i = 0, atts = el.attributes, n = atts.length; i < n; i++) {
                if(atts[i].nodeName.toLowerCase().indexOf(b[3].toLowerCase()) === 0) {
                    return true; 
                }
            }
            
            return false;
        }
    });
    
    //e.g:
    $('.slide:attrStartsWith("data-")').css('color', 'red');
    $('.slide:attrStartsWith("conf")').css('color', 'blue');
    
    
    1
    2

    If on the opposite side, you want to check for attribute ends with specific string, you can use:

    jQuery.extend(jQuery.expr[':'], {
        attrEndsWith: function (el, _, b) {
            for (var i = 0, atts = el.attributes, n = atts.length; i < n; i++) {
              var att = atts[i].nodeName.toLowerCase(),
                  str = b[3].toLowerCase();
                if(att.length >= str.length && att.substr(att.length - str.length) === str) {
                    return true; 
                }
            }
            
            return false;
        }
    });
    
    $('.slide:attrEndsWith("testID")').css('color', 'red');
    
    
    1
    2

提交回复
热议问题