How to get elements with contains text with help of jQuery

Get the elements which contains specified text inside the element(inner html)

In this post I am going to explain about how to get elements which elements have specified text in that innerhtml. For example I have list of items with some contains. So, now we want to get the element which contains “jQuery”.

Example here :-

Example html code :-

<ol id=”list” type=”digit”>

<li>I love <b>jQuery</b>.</li>
<li>Java script is Basic</li>
<li>Now a days jQuery is rocking</li>
<li>Thanks jQuery</li>

</ol>

script :-

<script type=”text/javascript” src=”http://jqueryui.com/latest/jquery-1.4.2.js”></script>

<script type=”text/javascript”>

$(function() {

//Here change font color only — we can use like too

//$(‘#list li:contains(“jQuery“)’).css(‘color’,’red’);

//If you want to apply multiple css style, use this

$(‘#list li:contains(“jQuery”)’).css({‘color’:’red’,’font-weight’:’bold‘});

});

</script>

Or

We can also apply for each element by looping, like this below. This we can use if we need to apply another functionality.

<script type=”text/javascript”>

$(function() {

$(‘#list li:contains(“jQuery”)’).each(function(){

$(this).css({‘color’:’red’,’font-weight’:’bold‘});

//.. Do something here.
});

});

</script>

See the out put below.

First it will show like this

  1. I love jQuery.
  2. Java script is Basic
  3. Now a days jQuery is rocking
  4. Thanks jQuery

After javascript runs then, output is like this. Wow!

  1. I love jQuery.
  2. Java script is Basic
  3. Now a days jQuery is rocking
  4. Thanks jQuery

The second item not contains “jQuery“.

I hope this helpful for you. if is there any better way, please let me know. Thanks for share.

Thanks to jQuery.

Enjoy while coding..!

Thanks,
Naga Harish.

Leave a Reply