Check if an element is a child of a parent

后端 未结 7 871
故里飘歌
故里飘歌 2020-12-07 19:54

I have the following code.



    

        
7条回答
  •  独厮守ぢ
    2020-12-07 20:06

    If you are only interested in the direct parent, and not other ancestors, you can just use parent(), and give it the selector, as in target.parent('div#hello').

    Example: http://jsfiddle.net/6BX9n/

    function fun(evt) {
        var target = $(evt.target);    
        if (target.parent('div#hello').length) {
            alert('Your clicked element is having div#hello as parent');
        }
    }
    

    Or if you want to check to see if there are any ancestors that match, then use .parents().

    Example: http://jsfiddle.net/6BX9n/1/

    function fun(evt) {
        var target = $(evt.target);    
        if (target.parents('div#hello').length) {
            alert('Your clicked element is having div#hello as parent');
        }
    }
    

提交回复
热议问题