Skip to content Skip to sidebar Skip to footer

Jquery.contains() Does Not Work Properly

I should get an 'alert' in the following case, but I am not getting any 'alert'. I am trying a simple example of jQuery.Contains().

Solution 1:

As per the jQuery documentation the API takes only element nodes (not JavaScript/jQuery objects or selectors)

Check to see if a DOM element is a descendant of another DOM element.

Only element nodes are supported; if the second argument is a text or comment node, $.contains() will return false.

Note: The first argument must be a DOM element, not a jQuery object or plain JavaScript object.

you should change the code to

$(function () {
   alert($.contains(document.body, $("p")[0])) //alerts truealert($.contains(document.body, document.getElementsByTagName("p")[0]));    //alerts true
})

Solution 2:

Try this:

$(document).ready(function(){
    var alpha = $.contains(document.body,$("p")[0])
    if (alpha) {
         alert(alpha);
    }
});

DEMO

Arguments are always DOM elements, not simple text.

For more details, see this.

Solution 3:

jQuery.contains only returns boolean and doe not have a callback. Try this code.

$(document).ready(function(){
    alert($.contains(document.body,$('p')[0]));
});

Solution 4:

Usethis code you have error on this line (var alpha = $.contains('body','p'){)
<html>
<head><scriptsrc="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script><script>
$(document).ready(function(){
var alpha = $.contains('body','p');
alert(alpha);
});
</script></head><body><p>This is a paragraph.</p></body>
</html>

Post a Comment for "Jquery.contains() Does Not Work Properly"