View Full Version : Who is higher?

08-01-2006, 07:39 AM
Hi All,

Given any two HTML elements, how do I find out who is higher up in the hierarchy?

08-01-2006, 07:46 AM
Not sure what you are asking. Can you rephrase your question better?

08-01-2006, 08:49 AM
This is my scenario:

Consider any two elements from a sample HTML page. Let them be <div> and <span>. Also let the <div> contain the <span>. Consider that the user clicks on the span, and keeping the mouse clicked, moves the pointer into the <div> and releases the mouse. I want to 'select' the <div>, since that is the highest possible parent for both <div> and <span>.

So now my question is this: given any two elements from a HTML page, how do I know who is higher up in the hierarchy? If I know this, I can move up from the lower hierarchy element and find out if the higher hierarchy element is in any way a parent. If yes, I'll 'select' the higher hierarchy element.

Hope my explanation is clear.

08-01-2006, 09:10 AM
if(parseFloat(document.getElementById('span_id1').offsetTop) < parseFloat(documengt.getElementById('span_id2').offsetTop)){
//span 1 is higher than span 2

like that??

08-01-2006, 09:52 AM
Thanx, boeing747fp!! offsetTop returns me the position of the element on the screen from the top. But dats not what i want. What I want is this:

Consider two elements, span1 and span2 in this document.


Now span2 is supposed to return 4. This is because span2 is present 4 levels down the HTML document. Likewise, span1 is supposed to return 3, body should return 2 and html should return 1.

08-01-2006, 10:11 AM
So use the parentNode property of each element to go up the tree until you find <body>.

08-01-2006, 10:15 AM
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"


<script language="JavaScript" type="text/javascript">
function MseD(){
var zxcevt=window.event||arguments.callee.caller.arguments[0];
var obj=zxcEventObj(zxcevt)
var els=document.getElementsByTagName('BODY')[0].getElementsByTagName('*');
for (var zxc0=0;zxc0<els.length;zxc0++){
if (els[zxc0]==obj){
alert(obj.tagName+' '+zxc0+'\n'+obj.title);

function zxcEventObj(zxce){
if (!zxce) var zxce=window.event;
if (zxce.stopPropagation) zxce.stopPropagation();
if (zxce.target) zxceobj=zxce.target;
else if (zxce.srcElement) zxceobj=zxce.srcElement;
if (zxceobj.nodeType==3) zxceobj=zxceobj.parentNode;
return zxceobj;


<span title="S1" >
Test 1
<span title="S2" >Test 2</span>


08-01-2006, 03:24 PM
... is there no property in Javascript for getting this?

08-01-2006, 09:24 PM
No, there is no property that indicates the hierarchical level an element is at.