Monday, May 30, 2016

Check the element is child of specific class element.

Some time we have the child element name, and want to check the element is inside the particular class or outside the class.

Please find below code to Check the element is child of specific class element.


<script type="text/javascript">function isChildOf(ChildObject,ContainerObject)
            {
                var retval=false;
                var curobj;
                if(typeof(ContainerObject)=="string")
                {
                    ContainerObject=document.getElementById(ContainerObject);
                }
                if(typeof(ChildObject)=="string")
                {
                    ChildObject=document.getElementById(ChildObject);
                }
                curobj=ChildObject.parentNode;
               // console.log(curobj.className+' '+ContainerObject.className);
               if(curobj==undefined) {
                return retval;
               }
                while(curobj!=undefined)
                {
                    if(curobj==document.body)
                    {
                        retval=false;
                        break;
                    }
                    if(curobj.className==ContainerObject.className)
                    {
                        retval =true;
                        break;
                    }
                    curobj=curobj.parentNode; //move up the hierarchy
                }
                return retval;
            }



var isChild = '';
         var child_Element = document.getElementsByClassName('childDIV');
                var tablinks = document.getElementsByClassName('parentDIV');
                for (var i = 0, j = tablinks.length; i < j; i++) {
                    var isChild = false;
                    //console.log(isChildOf(a[g],tablinks[i]));
                    if(isChildOf(child_Element,tablinks[i]) == true){
                        isChild = true;
                        break;
                    }
                }

 if(isChild == true){
        // YES child Element is in parent Element.
}

</script>

Cheers..:)

No comments:

Post a Comment