JQuery if this label contains this ... do it

I have an asp.net relay on the page. If each repeating element is wrapped in a label as follows:

<label class="ItemName">value</label> 

If this label contains the text "35", I want to display the text next to it. How can I do this using jquery ???

  jQuery(document).ready(function () { if ($('.ItemName').val().indexOf("35")) { $(this).val() = $(this).val() + "some text"; } }); 
+1
jquery class label
Sep 09 '10 at 15:12
source share
4 answers
  • The this function in the .ready function must refer to document .
  • To get text content, use .text() instead of .val() .
  • To update some value, use $obj.val(blah); , not $obj.val() = blah; . (This is actually a limitation of Javascript.)
  • There is :contains() selector for filtering elements containing some text.
  • To add any text (or HTML), the .append() method already exists (Thanks @JP for this.)

Instead, you might want to:

 $('.ItemName:contains(35)').append("some text"); 
+5
Sep 09 '10 at 15:15
source share

indexOf returns -1 if not found, or an index. Do it:

 if ($('.ItemName').val().indexOf("35") >= 0) { 
0
Sep 09 '10 at 15:13
source share

.text() should work:

 var item = $('.ItemName'); if ( item.text().indexOf("35") > -1 ) { item.after("some text"); } 
0
09 Sep '10 at 15:14
source share

do you mean that?

 jQuery(document).ready(function () { if ($('.ItemName').text().indexOf("35")) { $(this).text($(this).text() + "some text"); } }); 
0
Sep 09 '10 at 15:14
source share



All Articles