Case-insensitive attribute-value selector with Jquery

后端 未结 3 1893
名媛妹妹
名媛妹妹 2020-12-01 18:49

I need to get the value of the content attribute of a certain meta tag.

var someContent = $(\"meta[name=someKindOfId]\").attr(\"con         


        
相关标签:
3条回答
  • 2020-12-01 19:04

    How about this?

    You can reuse the case-insensitive jQuery expression, as shown in the snippet below (execute it to see how the first div matches, while the second does not).

    $.expr[':'].iAttrContains = function(node, stackIndex, properties){
        var args = properties[3].split(',').map(function(arg) {
            return arg.replace(/^\s*["']|["']\s*$/g, '');  
        });
        if ($(node).attr(args[0])) {
            //exact match:
            return $(node).attr(args[0]).toLowerCase() == args[1].toLowerCase();
            //if you actually prefer a "contains" behavior:
            //return -1 !== $(node).attr(args[0]).toLowerCase().indexOf(args[1].toLowerCase());
        }
    };
    
    $("div:iAttrContains('data-name', 'test')").addClass('matched');
    div{background:red;}
    div.matched{background:green;}
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
    
    <div data-name="This is a test">First div</div>
    <div data-name="This is a div">Second div</div>

    0 讨论(0)
  • 2020-12-01 19:20

    You could use the jquery filter function like so

    var meta = $('meta[name]').filter(function() {
        return this.name.toLowerCase() == 'somekindofid';
    });
    

    Based upon CSS selector case insensitive for attributes

    http://jsfiddle.net/nickywaites/mkBvC/

    0 讨论(0)
  • 2020-12-01 19:25

    Also, for case insensitive attribute *= selector:

    $("meta[name*=someKindOfId]")
    

    You can use:

    $('meta').filter(function() {
           return (/somekindofid/i).test($(this).attr('name'));
    }).attr("content")
    
    0 讨论(0)
提交回复
热议问题