.contains() throws an error "Uncaught TypeError: Object [object Object] has no method 'contains' "

StackOverflow https://stackoverflow.com/questions/21524356

  •  06-10-2022
  •  | 
  •  

Question

I do have a working code (with :contains), but I couldn't make it work with .contains(), and I would like to ask why. HTML:

<div id="quiz_score_percent">Your score: <em class="placeholder">100</em> %</div>
<div id="quiz_summary">
<p>quiz feedback</p>

JS (working, doesn't need change):

$(document).ready(function () {
 if ($("#quiz_score_percent").has(":contains('100')").length) {
    console.log("test");
    $("#quiz_summary").append("<p>test text</p>");

}

});

But with .contains() :

if ($("#quiz_score_percent").contains('100')){/* execute */} 

it throws:

Uncaught TypeError: Object [object Object] has no method 'contains'

JS fiddle here: JS fiddle code

Why doesn't .contains() work? The accepted solution here wouldn't work for me...

Was it helpful?

Solution

:contains and .contains() are two different animals

  • :contains will check if a certain text ist contained in the inner HTML of the selector.
  • $.contains(container, contained) checks if a given element (the second parameter) is a child of the selector (the first parameter). 100 is not a HTML node/jQuery element. (thx for the hint, Frédéric!)

See http://api.jquery.com/jQuery.contains/ and http://api.jquery.com/contains-selector/.

OTHER TIPS

Try this:

if ($("#quiz_score_percent").contains('100') == true){/* execute */}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top