Solved

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

Posted on 2003-11-02
18
872 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 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
Salesforce Made Easy to Use

On-screen guidance at the moment of need enables you & your employees to focus on the core, you can now boost your adoption rates swiftly and simply with one easy tool.

 
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
 
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

Free Tool: Site Down Detector

Helpful to verify reports of your own downtime, or to double check a downed website you are trying to access.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Title # Comments Views Activity
How to refresh a page from a sub domain in ajax ? 34 46
Put POST values into cookies. 14 34
Glitching Slide Show 19 27
How do I split a variable to newline 2 17
JavaScript has plenty of pieces of code people often just copy/paste from somewhere but never quite fully understand. Self-Executing functions are just one good example that I'll try to demystify here.
Today, the web development industry is booming, and many people consider it to be their vocation. The question you may be asking yourself is – how do I become a web developer?
Viewers will learn one way to get user input in Java. Introduce the Scanner object: Declare the variable that stores the user input: An example prompting the user for input: Methods you need to invoke in order to properly get  user input:
Explain concepts important to validation of email addresses with regular expressions. Applies to most languages/tools that uses regular expressions. Consider email address RFCs: Look at HTML5 form input element (with type=email) regex pattern: T…

733 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