gshaffer gshaffer - 3 months ago 9
Javascript Question

Case insensitive jQuery attribute selector

I am doing the following using attribute contains selector $('[attribute*=value]')

<input name="man-news">
<input name="milkMan">

<script>
$( "input[name*='man']").css("background-color:black");
</script>


This works for the 1st input but not the second input as "Man" has a capital "M"

How can I make
$( "input[name*='man']")
an case insensitive selector?

Answer

You can always use .filter():

var mans = $('input').filter(function() {
    return $(this).attr('name').toLowerCase().indexOf('man') > -1;
});

mans.css('background-color', 'black');

The key part here is toLowerCase() which lowercases the name attribute, allowing you to test it for containing man.