Go Premium for a chance to win a PS4. Enter to Win

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 884
  • Last Modified:

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

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
JontyDunne
Asked:
JontyDunne
  • 7
  • 5
  • 2
  • +3
3 Solutions
 
proziathCommented:
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
 
devicCommented:
easy way is : <div onclick=alert(this.parentNode.nodeName)> hello world</div>

anywhere & anytime ;)
0
 
NushiCommented:
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
Industry Leaders: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 
devicCommented:
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
 
proziathCommented:
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
 
devicCommented:
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
 
NushiCommented:
devic
that very similar to what im writing now.
thats the way to solve it.

Nushi.
0
 
NushiCommented:
one comment:

parentNode == NS
parent == IE.

you have to set the object based on browser.

Nushi.
0
 
devicCommented:
hi Nushi,

oops, parentNode for IE too.

is W3C DOM (IE5+, NN6+)
0
 
NushiCommented:
:-))
0
 
NetGrooveCommented:
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
 
NushiCommented:
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
 
devicCommented:
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
 
NushiCommented:
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
 
VincentPugliaCommented:
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
 
NushiCommented:
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
 
jaysolomonCommented:
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

Industry Leaders: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

  • 7
  • 5
  • 2
  • +3
Tackle projects and never again get stuck behind a technical roadblock.
Join Now