14

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.

Josh Johnson
  • 10,729
  • 12
  • 60
  • 83
  • See this post, pretty good solution: http://stackoverflow.com/questions/187537/is-there-a-case-insensitive-jquery-contains-selector – Eli Apr 22 '11 at 13:16

3 Answers3

27

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/

Community
  • 1
  • 1
Nicky Waites
  • 2,428
  • 18
  • 19
  • 1
    Perfect. var someContent = $('meta[name]').filter(function() { return this.name.toLowerCase() == 'somekindofid'; }).attr("content"); – Josh Johnson Apr 22 '11 at 13:45
  • Something I noticed with that solution Josh is that it will only return the content for 1 meta tag. I'm not sure if you'd have multiple meta tags with the same name but here's an updated fiddle - http://jsfiddle.net/nickywaites/mkBvC/1/ – Nicky Waites Apr 22 '11 at 15:04
  • This is a working solution, but not very reusable. Please check my jQuery expression answer. :) – alexcasalboni Jul 20 '15 at 09:53
5

Also, for case insensitive attribute *= selector:

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

You can use:

$('meta').filter(function() {
       return (/somekindofid/i).test($(this).attr('name'));
}).attr("content")
Erik Aronesty
  • 11,620
  • 5
  • 64
  • 44
Flash
  • 15,945
  • 13
  • 70
  • 98
0

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>
alexcasalboni
  • 1,726
  • 1
  • 16
  • 26