How do I use jQuery to ignore case when selecting?
Asked Answered
A

4

16

I'm currently attempting to disable a link using the following jQuery selector:

$("a[href$=/sites/abcd/sectors]").removeAttr("href");

The problem is that sometimes the href might not always be lower case on the page. When this happens the selector no longer matches.

Does anyone know how to get around this? Can I change the behaviour this once to ignore case?

Antiperistalsis answered 6/3, 2009 at 17:5 Comment(3)
Are you using the latest version of jQuery? Because I just tested that selector in FF with 1.3.2 on a page with both uppercase HREF and lowercase href, and it matched both every time. What browser are you getting that problem on?Whippoorwill
jQuery 1.3.2 with IE 7 - just double-checked and problem is still happening.Antiperistalsis
@cdmckay: I think the OP meant that the URL might not always be lower case.Bergstein
F
14

I ran into this myself. I switched the logic a bit to allow me to compare it without case. It requires a little more work, but at least it works.

$('a').each(function(i,n) {
    var href = $(n).attr("href");
    href = href.toLowerCase();
    if (href.endsWith('/sites/abcd/sectors'))
        $(n).removeAttr('href');
});

You would have to figure out your own endsWith logic.

Fonsie answered 6/3, 2009 at 17:11 Comment(2)
Thanks, that worked well. I used a regex for the endsWith. By the way, toLower() should be toLowerCase().Antiperistalsis
Ah, thanks. I did this from memory and forgot a chunk. I've updated it.Fonsie
S
5

jQuery was built to be extended. You can correct it or add your own type of case-insensitive selector.

Rick Strahl: Using jQuery to search Content and creating custom Selector Filters

Steradian answered 6/3, 2009 at 20:49 Comment(0)
D
1

You may use function "is" in jQuery. It is not case-sensitive.

   $("a").each(function() {
     if ($(this).is("a[href$=/sites/abcd/sectors]")) {
       $(this).removeAttr('href');
     }
   })
Duplet answered 30/7, 2012 at 10:56 Comment(0)
A
1

First this is NOT VALID expression since it contains \ ,

If you wish to use any of the meta-characters ( such as !"#$%&'()*+,./:;<=>?@[\]^``{|}~ ) as

a literal part of a name, you must escape the character with two backslashes: \\.

Src : http://api.jquery.com/category/selectors/

so you must escape the / to \\/

so your expression will be $("a[href$=\\/sites\\/abcd\\/sectors]").removeAttr("href");

Anaemia answered 21/9, 2012 at 15:22 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.