Case-insensitive attribute-value selector with Jquery

℡╲_俬逩灬. 提交于 2019-11-26 14:28:58

问题


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

var someContent = $("meta[name=someKindOfId]").attr("content");

is how I usually do it. For business reasons, someKindOfId may be somekindofid. It could be other combinations of cases as well. I don't know.

What is the best way to search for this meta tag? Adding an id or other identifier is out of the question.


回答1:


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/




回答2:


Also, for case insensitive attribute *= selector:

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

You can use:

$('meta').filter(function() {
       return (/somekindofid/i).test($(this).attr('name'));
}).attr("content")



回答3:


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>


来源:https://stackoverflow.com/questions/5755722/case-insensitive-attribute-value-selector-with-jquery

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!