Solved

Check if an element is a child of another element using DOM

Posted on 2003-11-02
18
868 Views
Last Modified: 2013-11-19
Hi there,

Is there a method in the DOM that checks to see if a node is the child of some specified element?

For example:

       object.isChild(of an element)  <-------- Something like this?

Thanks,

Jonty
0
Comment
Question by:JontyDunne
  • 7
  • 5
  • 2
  • +3
18 Comments
 
LVL 2

Accepted Solution

by:
proziath earned 168 total points
ID: 9665656
Try the following. What you need is the ParentNode property of the element and the nodeName actually holds the name of the parent in this case

<html>
<head>
  <title></title>
</head>
<body>
<SCRIPT>
function f()
{
var parent = div1.parentNode;
alert(parent.nodeName);
}
</SCRIPt>

<BODY onclick=f()>
<div ID=div1> hello world</div>
</BODY>


</body>
</html>

0
 
LVL 25

Expert Comment

by:devic
ID: 9665660
easy way is : <div onclick=alert(this.parentNode.nodeName)> hello world</div>

anywhere & anytime ;)
0
 
LVL 10

Expert Comment

by:Nushi
ID: 9665664
you can do something like that:

get your element.
check to se if this element is one of the children of the parent.
you will have to do it recursivly by running on all of the parent.chilrens
object.

flow:
1. get "parent" eleemnt + "target" element
2. get children at position X
3. check to see if the target is one of the parent.children eleemnts.

i will try to wirte you a sample code in few minutes.

Nushi.
0
 
LVL 25

Expert Comment

by:devic
ID: 9665681
here is with attach event, to click without to write event in to element
=======================================
<html>
<head>
 <title></title>
 <script>
 function init()
 {
       document.body.onclick=viewParentNode;
 }
 
function viewParentNode()
{
      alert("nodeName="+event.srcElement.nodeName+"\nParentNodeName="+event.srcElement.parentNode.nodeName)
}
</script>

</head>
<body onload=init()>

<table width=555 cellspacing=0 cellpadding=0 border=1>
      <tr><td>kuku</td><td>lala</td></tr>
      <tr><td><div>kuku</div></td><td><span>lala</span></td></tr>
      <tr><td><p>kuku</p></td><td><u>lala</u></td></tr>
</table>

<div>
<span>
kuku click here too
</span>
</div>
</body>
</html>
0
 
LVL 2

Expert Comment

by:proziath
ID: 9665689
Since I could find no built in system for checking if an element is a child of a specified elemnt in th DOM, how about the following that allows you to specify the parent and it will check if the child element is trully the child of your specified parent.

<html>
<head>
  <title></title>
</head>
<body>
<SCRIPT>
function f(obj)
{var p;
var parent = obj.parentNode;
p=prompt("enter the parent ID");
if(parent.id==p)
 alert("yes, it is child of element "+p);
 else
  alert("No, it is not child of element "+p);
}
</SCRIPt>

<BODY id="b">
<div ID="div1" onclick=f(this)> CLICK HERE FIRST</div>
<br>
<br>
<br>
<div ID="div2"><font id="f1" onclick=f(this)>CLICK HERE NEXT</font></div>

</BODY>


</body>
</html>

0
 
LVL 25

Expert Comment

by:devic
ID: 9665702
be careful with recursive functions! ;)

ok here, my recursive function:
===================================
<html>
<head>
<title></title>
<script>
//created by devic! =)
function init()
{
     document.body.onclick=viewParentNode;
}
var level;
var result;
function viewParentNode(obj,result)
{
    if(!obj){obj=event.srcElement}
      if(!result){result=""}
      if(!level){level=0}
      result+="level"+level+": nodeName="+obj.nodeName+"\n"
      if(obj.parentNode)
      {
            level++;
            viewParentNode(obj.parentNode,result);
      }
      else
      {
            level=0;
            alert(result);
            return;
      }
}
</script>

</head>
<body onload=init()>

<table width=555 cellspacing=0 cellpadding=0 border=1>
    <tr><td>kuku</td><td>lala</td></tr>
    <tr><td><div>kuku</div></td><td><span>lala</span></td></tr>
    <tr><td><p>kuku</p></td><td><u>lala</u></td></tr>
</table>

<div>
<span>
kuku click here too
</span>
</div>
</body>
</html>
0
 
LVL 10

Expert Comment

by:Nushi
ID: 9665704
devic
that very similar to what im writing now.
thats the way to solve it.

Nushi.
0
 
LVL 10

Expert Comment

by:Nushi
ID: 9665706
one comment:

parentNode == NS
parent == IE.

you have to set the object based on browser.

Nushi.
0
Find Ransomware Secrets With All-Source Analysis

Ransomware has become a major concern for organizations; its prevalence has grown due to past successes achieved by threat actors. While each ransomware variant is different, we’ve seen some common tactics and trends used among the authors of the malware.

 
LVL 25

Expert Comment

by:devic
ID: 9665718
hi Nushi,

oops, parentNode for IE too.

is W3C DOM (IE5+, NN6+)
0
 
LVL 10

Expert Comment

by:Nushi
ID: 9665722
:-))
0
 
LVL 10

Expert Comment

by:NetGroove
ID: 9665726
Here my example:


<htm>
<head>
<script>

function isChild(sObj) {
  if(this.parentNode==sObj){
    alert("is Child of dblClicked Row.")
  } else {
    alert("is NOT a child of dblClicked object.");
  }
}

var someObj;

function init(){
  theTab = document.createElement('table');
  document.body.appendChild(theTab);
  tBody = document.createElement('tbody');
  theTab.appendChild(tBody);
  for(r=0;r<9;r++){
    newRow = document.createElement('tr');
    newRow.ondblclick = function(){someObj = this;};
    tBody.appendChild(newRow);
    for(c=0;c<9;c++){
      newCell = document.createElement('td');
      newRow.appendChild(newCell);
      newCell.innerHTML = (r*9+c);
      newCell.isChild = isChild;
      if(c>2){
        newCell.onclick = function(){this.isChild(someObj);};
      }
    }
  }
}
</script>
</head>
<body onLoad="init()">
</body>
</html>


Usage: doubleclick on one of the first three columns of a row to set the parent row.
Single click on columns greater three does say if that cell is child of last double clicked row.

0
 
LVL 10

Expert Comment

by:Nushi
ID: 9665736
im working on something more simple.
its not complete yet but it will "print" the tree (DOM) of the objects.

the last thing to do (beside debugging) is to
check the needed parent against the childrens.

you need to test the child in the function and if you find it to
exit/ alert / return flag etc.

its not complete yet. but you will get the concept.

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">

<html>
<head>
      <title>Untitled</title>
</head>

<body>
<table>
      <tr>
            <td>radio1: <input type='radio' name='radio1'></td>
      </tr>
</table>
<br>
<br>
<span id='structure'>

</span>
<script>

var tab = '';      
function showChildrens( obj ){
      tab += '&nbsp;&nbsp;&nbsp;&nbsp;';      
      
      if (!obj)
            return;
      
      for (ind=0; ind<obj.children.length ; ind++){
            document.getElementById('structure').innerHTML += '<br>' + tab + obj.children(ind).tagName;
            showChildrens( obj.children( ind  ));
            }
      }      
//      START PRINTING ALL THE CHILDRENS OF THE BODY
showChildrens( document.body );

</script>

</body>
</html>


Nushi.

0
 
LVL 25

Assisted Solution

by:devic
devic earned 166 total points
ID: 9665826
Nushi:

for input is very interestingly which type has the input:

==================================
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">

<html>
<head>
    <title>Untitled</title>
</head>

<body>
<table>
    <tr>
         <td>radio1: <input type='radio' name='radio1'></td>
    </tr>
</table>
<br>
<br>
<span id='structure'>

</span>
<script>

var tab = '';    
function showChildrens( obj ){
    tab += '&nbsp;&nbsp;&nbsp;&nbsp;';    
     
    if (!obj)
         return;
   
     for (ind=0; ind<obj.children.length ; ind++){
         document.getElementById('structure').innerHTML += '<br>' + tab + obj.children(ind).tagName+getType(obj.children(ind));
         showChildrens( obj.children( ind  ));
         }
    }
function getType(obj)    
{
      if(obj.type)return " <font size=-1>type:"+obj.type+"</font>";
      return "";
}
//     START PRINTING ALL THE CHILDRENS OF THE BODY
showChildrens( document.body );

</script>

</body>
</html>
0
 
LVL 10

Expert Comment

by:Nushi
ID: 9665832
its only for display purposes.
he only has to know the children of a parent.
i typed it only to show the recurstion in work.

he will have to swicth the prinitg with the obj he want to check equals to.

Nushi.
0
 
LVL 15

Assisted Solution

by:VincentPuglia
VincentPuglia earned 166 total points
ID: 9665874
Hi Jonty,

I'm going to presume this question has something to do with your last question & that you already have enough info on 'parentNode' and 'listener':


function addEventAttr(obj)
{
var dad = obj.parentNode;
obj.setAttribute("onmouseover", dad.className = 'over');

if (dad.id == 'a')
{

obj.attachEvent("onmouseout", function(){dad.className='special'});
}
}
//-->
</script>
<style>
td {
background-color:white;
}

td.over{
background-color:red;
}
td.special {
background-color:lime;
}
</style>
</head>
<body>
<table border="1">
<tr>
<td id="a"><a href="http://members.aol.com/grassblad" onmouseover='addEventAttr(this)'>GrassBlade Javascript</a></td></tr>
<tr><td><a href="http://www.webxpertz.net/forums" onmouseover='addEventAttr(this)'>Webxpertz Forums</a></td></tr>
</table>

Vinny
0
 
LVL 10

Expert Comment

by:Nushi
ID: 9837104
hi there  JontyDunne

i thisnk its about time to close the question.
i think you should split the points between all this who spent their time helping you out.

Nushi.

0
 
LVL 16

Expert Comment

by:jaysolomon
ID: 10346693
No comment has been added lately, so it's time to clean up this TA.
I will leave the following recommendation for this question in the Cleanup topic area:

Split: proziath {http:#9665656} & devic {http:#9665826} & VincentPuglia {http:#9665874}

Please leave any comments here within the next four days.
PLEASE DO NOT ACCEPT THIS COMMENT AS AN ANSWER!

jAy
EE Cleanup Volunteer
0

Featured Post

What Security Threats Are You Missing?

Enhance your security with threat intelligence from the web. Get trending threat insights on hackers, exploits, and suspicious IP addresses delivered to your inbox with our free Cyber Daily.

Join & Write a Comment

SASS allows you to treat your CSS code in a more OOP way. Let's have a look on how you can structure your code in order for it to be easily maintained and reused.
This article discusses how to create an extensible mechanism for linked drop downs.
The viewer will learn the benefit of using external CSS files and the relationship between class and ID selectors. Create your external css file by saving it as style.css then set up your style tags: (CODE) Reference the nav tag and set your prop…
The viewer will the learn the benefit of plain text editors and code an HTML5 based template for use in further tutorials.

744 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

15 Experts available now in Live!

Get 1:1 Help Now