Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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().

<html>
    <head>
        <script src="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>
like image 849
Deadpool Avatar asked Dec 14 '22 15:12

Deadpool


1 Answers

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 true
   alert($.contains(document.body, document.getElementsByTagName("p")[0]));    //alerts true
})
like image 89
vdua Avatar answered Dec 27 '22 07:12

vdua