Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JQuery - How can I write a case-insensitive 'Attribute Contains' selector?

I'm trying to write a userscript for YouTube that will select all videos on a page based on their titles, which are also set as the thumbnail images' title attribute.

The following works just fine, but it's case sensitive:

var videoTitle = "the";

$('img[title*="'+videoTitle+'"]').each(function() {

// stuff here

});

The selector above will match any video with "the" in the title, but not "The" or "THE", for example.

I did read that I could use .filter() to accomplish this somehow, but I'm not sure how that works, and I couldn't find an example that would fit my scenario successfully.

I tried something like this, based on an example I found on StackOverflow, but it doesn't work:

$('img[title]').filter(function(){return this.title.toLowerCase() == videoTitle}).each(function() {

// stuff here

});
like image 534
vertigoelectric Avatar asked Oct 21 '11 18:10

vertigoelectric


2 Answers

This is adapted from a post by Karl Swedburg on the jQuery docs page for the 'Attributes Contains Selector'. It uses a RegEx and the i case insensitive switch along with the filter function -

<img title="Star Wars"/>
<img title="Star Wars 2"/>
<img title="Star Wars 3"/>
<img title="Back To The Future"/>

var videoTitle = "star wars";
var re =  RegExp(videoTitle ,"i"); 
$('img[title]').filter(function() {
   return re.test(this.title);
}).each(function() {alert(this.title)});

The names of the three 'Star Wars' films should be alerted.

Demo - http://jsfiddle.net/FKBTx/3

like image 156
ipr101 Avatar answered Sep 28 '22 01:09

ipr101


Example -

$('img').filter(function(){
    return this.title.match(RegExp(videoTitle ,"i"))
}).each(function(){
        alert(this.title);
})
like image 41
Jayendra Avatar answered Sep 28 '22 00:09

Jayendra