In this post I am going to explain about jQuery Contains method with case insensitive.
First small talk about jQuery, It one of the popular java script library which is ready to use. The jQuery’s tag line is “WRITE LESS, DO MORE.” I feel it is true, because we can get more functionality with less code lines.
Just few days before, I worked with jQuery Selector using Contains. Contains is returns the elements which are the elements have that part of text. But, I faced a problem. For example I am search for “ABC” $(‘#ShowItems li:contains(“ABC”)’). It is not showing “abc” contains elements. Because, Contains method is case sensitive.
So, I found a way to make jQuery selector contains extender. This we can do in jQuery easily.
we need to add this script
//Extend selector
$.extend($.expr[‘:’], {
‘containsi’: function (elem, i, match, array) {
/* For example $(‘#ShowItems li:containsi(“Share”)’), then match[3] will be Share*/
return (elem.textContent || elem.innerText || ”).toLowerCase().indexOf((match[3] || “”).toLowerCase()) >= 0;
}
});
Full HTML Code :-
<head>
<title>Jquery Contains with case-[in]sensitive</title>
</head>
<body>
<ul id=”ShowItems”>
<li>Share Our Ideas</li>
<li>More you share, More you gain</li>
<li>Enjoy while coding..!</li>
</ul>
<script src=”http://code.jquery.com/jquery-1.5.1.min.js” type=”text/javascript”></script>
<script type=”text/javascript”>
//Extend selector
$.extend($.expr[‘:’], {
‘containsi’: function (elem, i, match, array) {
/* For example $(‘#ShowItems li:containsi(“Share”)’), then match[3] will be Share*/
return (elem.textContent || elem.innerText || ”).toLowerCase().indexOf((match[3] || “”).toLowerCase()) >= 0;
}
});
//This is contains will look with case sensitive
$(‘#ShowItems li:contains(“Share”)’).css(‘color’, ‘red’);
//This is for case-insensitive
$(‘#ShowItems li:containsi(“Share”)’).css(‘text-decoration’, ‘underline’);
</script>
</body>
</html>
The out put will come like this
- Share Our Ideas
- More you share, More you gain
- Enjoy while coding..!
First when I try with Contains like this
//This is contains will look with case sensitive
$(‘#ShowItems li:contains(“Share“)’).css(‘color’, ‘red’);
it only returning first one which contains Share, case sensitive.
When I try to call containsi selector
$(‘#ShowItems li:containsi(“Share“)’).css(‘text-decoration’, ‘underline’);
it is returns 2 elements, which having “Share” and “share“. Here it is case insensitive.
Jquery makes my work easy! I love it!
Enjoy while coding..!
Thanks,
Naga harish.