0

I have two paragraphs:

<p>Some text</p>
<p>Another text</p>

and this jQuery code:

if ( $("p:contains('Right text')") ) {
  alert("Matching!");
};


$( "p:contains('Right text')" ).css( "text-decoration", "underline" );

It should display an alert only if there's text Right text. But when you load the page, it displays everytime. Second part of the script should add underline to paragraph with Right text and it works - if it contains Right text, it has the underline.

Why my code doesn't work, although the selector is same? How can I display an alert if there's right text?

http://codepen.io/anon/pen/mEvOWA?editors=1010

Szymon Marczak
  • 1,055
  • 1
  • 16
  • 31
Karolina Ticha
  • 531
  • 4
  • 19

3 Answers3

2

That's because the JQuery object will be converted to a boolean for the condition. If it doesn't match, it will be a JQuery object of length:0, but still be converted into true. It only be converted into false if it was 0, -0, null, false, NaN, undefined.

Try this instead:

if ( $("p:contains('Right text')").length ) {
  alert("Matching!");
}
MyStream
  • 2,533
  • 1
  • 16
  • 33
1

$("p:contains('Right text')") always returns an array. This array is defined, so if you try to convert it to boolean, you always get true. Check the length of the array - it should be greater than 0.

Right code:

if ( $("p:contains('Right text')").length > 0 ) {
  alert("Matching!");
};


$( "p:contains('Right text')" ).css( "text-decoration", "underline" );

Note: if there's Right text blah blah it will have the underline too, because it contains Right text. If you want to check full content do

$( "p" ).each(function() {
    if ( $( this ).html() == "Right text" ) {
        alert( "Matching" );
        $( this ).css( "text-decoration", "underline" );
    }
});
Szymon Marczak
  • 1,055
  • 1
  • 16
  • 31
1

try using a for-each and then get the string text of each tag p and use indexOf to find the position of the string that you want to match if the string is found the position is all's > -1 other wise it will be -1 in case it isn't a match

$('p').each(function(){
    if( $(this).text().indexOf('code example') > -1){
        console.log($(this).text());
    }
});
H.C
  • 565
  • 7
  • 28
  • forgot to had the text must have copied a previous version of the code when testing never less thx for -1. – H.C Aug 13 '16 at 17:27
  • Your answer is unclear a bit (anyway, I'll keep +1 on). Do steps, e.g. 1. Blah blah blah. 2. Blah blah blah. 3. Blah blah blah. Don't stick the text together. – Szymon Marczak Aug 13 '16 at 18:57