Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

DOM search function, selected object is a on branch of a known parent

Status
Not open for further replies.

unlocked291

Technical User
Jan 2, 2010
2
US
Hi.

Everywhere I see functions that go down the branches from the higher elements to lower ones. It seems easy this way to search if a selected object it is or it is not part of a determined parent. I am wondering if there is a way for doing it from the lower element, without going down the branch by selecting siblings, but going up by selecting parents?

For example:
...
<form>
...
<div> <p>A</p> </div>
</form>
<p>B</p>

We take as reference "form". How will look a function that tells me the text node "A" is under the "form" node; and when applied to "B" it tells me it is not. I want to go up the branches (brake on body I guess), not the other way around.
 
Every element object has a parentNode property which you can query to traverse up the parent hierarchy, e.g:

Code:
aTextNode.parentNode; // would be the <p> surrounding "A"
aTextNode.parentNode.parentNode; // would be the <div>
aTextNode.parentNode.parentNode.parentNode; // would be the <form>

You can use a while loop to traverse right the way up to the top level node:

Code:
var theNode = startingNode;
while (theNode) {
   // do something
   theNode = theNode.parentNode;
}

Hope this helps,
Dan



Coedit Limited - Delivering standards compliant, accessible web solutions

Dan's Page [blue]@[/blue] Code Couch:
Code Couch Tech Snippets & Info:
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top