How can I tell if an element only contains a J character with JQuery?

Let's say I have 2 divs:

<div>&pound; 21.99</div>
<div>&pound;</div>

      

If I only want to select the div containing & pound; just a symbol, how would I do it?

I tried:

if ($('div:contains("&pound;")').length > 0) 
{
   $(this).addClass("pound");
}

      

+2


source to share


4 answers


I believe the problem is that the browser is converting HTML escape characters, so you have to look for the actual character ... I tested this and it works



$(document).ready(function(){
 $('div').each(function(){
  if ($(this).html() == "ยฃ"){
   $(this).addClass("pound");
  }
 })
})

      

+4


source


$('div:contains("&pound;")').each( function() {
     var text = $(this).html();
     if (text && text.match(/\s*&pound;\s*/)) {
        $(this).addClass('pound');
     }
});

      



+1


source


Try .filter.

I found another question on SO with related information:

JQuery expression validation

0


source


The tvanfosson code allows spaces on either side of the ยฃ sign, but the regexp can have a slight modification:

$('div:contains("&pound;")').each( function() {
    var text = $(this).html();
    if (text && text.match(/^\s*&pound;\s*$/)) {
        $(this).addClass('pound');
        }
    });

      

notice the "^" and "$" indicating the beginning and end of the line.

0


source







All Articles