Jquery, how to check if a particular id is a child of another id?

I have a specific id ("mysubid"), now I want to check if this element (this id) is in the child path of another id ("mymainid").

Is there an easy way to do this or will I go up, element by element, to see if the element is in a child path.

On the children's path, I say something like this:

A> B> C> D

So D is in the child path of A, B and C

+3
source share
7 answers

You all make it very difficult. Use the descendant selector :

if ($('#mymainid #mysubid').length) {
    // #mysubid is inside #mymainid
}
+10
source
var isInPath = $("#mysubid").closest("#mymainid").length > 0;
+4
  if( $("#mymainid").find("#mysubid").length > 0 )
+2
if($('#mysubid','#mymainid').length)
{

}

, #mysubid #mymainid

jQuery( selector, [ context ] )
  • selector: ,
  • : DOM, jQuery

overlaod $('#mymainid').find('#mysubid').lentgh btw, : http://github.com/jquery/jquery/blob/master/src/core.js#L162

, , $('#a #b') Sizzle Selector , $('#a',$('#b')), witch javascript getElementById

: jQuery , , .

+1

, elm.parentNode . , ( ) POJ, :

var doc = document,
child = doc.getElementById("mysubid"),
parent = doc.getElementById("mymainid"),
getParents = function (elm) {
    var a = [], p = elm.parentNode;
    while (p) {
        a.push(p);
        p = p.parentNode;
    }
    return a;
};
getParents(child).indexOf(parent);
+1
source

I tried in different browsers, and the DOM function below is 3-10 times faster than the selection methods (jQuery or document.querySelectorAll)

    function is(parent){
        return {
            aParentOf:function(child){
                var cp = child.parentNode;
                if(cp){
                    return cp.id === parent.id ? 
                       true : is(parent).aParentOf(cp);
                }
            }
        }
    }

The call below will return true if A is the parent of D

is(document.getElementById('A')).aParentOf(document.getElementById('D'))

For a few calls, I would use. $('#A #D').length
For very frequent calls, I would use the DOM.

+1
source

Using the 'is' method actually returns a boolean value.

if($('#mymainid').is(':has(#mysubid)')) // true

Going in another direction ...

if($('#mysubid').parents('#mymainid').length) // 1
0
source

Source: https://habr.com/ru/post/1766415/


All Articles