Using Jquery Contains

Using JQuery Contains

In this tutorial we are going to see about the very useful jquery contains() method. This method is very useful to check whether a DOM component is within another DOM component. In the following example I have created a html file that contains list items and a button used to add a highlight class to the list item which contains “Browser” text



jquery contains() method syntax

jQuery.contains( container, contained )
  • container — The DOM component which may include the other component.
  • contained — The DOM component which may be included by the other component.

jquery contains() method example

 <html>
	<head>
		<title>JQuery Contains() Method Example/title>
		<style type="text/css">
			.highlight{
				background: orange;
			}
			body{
				width: 200px;
			}
		</style>
		<script src="jquery-1.8.3.js"></script>
		<script>
		    $(function(){
		    	var btn=$('button');
		    	$('button').toggle(function(){
		    		$('li:contains(Browser)').addClass('highlight');
		    		btn.text('Remove Style');
		    	},
		    	function(){
		    		$('li').removeClass('highlight');
		    		btn.text('Add Style');
		    	})
			});
	    </script>
	</head>
	<body>
			<ul>
				<li>Chrome - Browser</li>
				<li>Firefox - Browser</li>
				<li>Windows 8 - OS</li>
				<li>Android - OS</li>
				<li>Safari - Browser</li>
				<li>Machintosh - OS</li>
				<li>Facebook - Social</li>
				<li>Twitter - Social</li>
				<li>Google - Search Engine</li>
				<li>Google Plus - Social</li>
				<li>Bing - Search Engine</li>
			</ul>
			<button>Add Style</button>
	</body>
</html>


Try the below jquery contains working demo

Code Explanation For JQuery Beginners

So in the above example we have a list of items containing name of the browsers, os, social, and search engines. Inside the anonymous function call we are checking whether the list item contains the word browser, once it is found we are adding highlight class to that list item.

The highlight class simply change the background to Orange color.

And to improve this code, I have added a toggle button. Inside the ON state function of the toggle we are adding the highlight class to the list item using the addClass(). And in the OFF state are removing the highlight class from the list item using the removeClass() method.


From this jquery contains example tutorial, we have taken a look at how to check whether a DOM component is within another DOM component in a html page using jquery contains() methods.

Leave a Reply

Scroll To Top

Foolow Me on Google Plus

VimalTuts on Twitter
61 people follow VimalTuts
ShankargAdhamsheabhijeetminkyuuusuper_phShajeelAMageshKemeoluoi_