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 wOOdy-Soft on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Selecting parents of a child node (JavaScript, DOM)

Status
Not open for further replies.

Protonman

Programmer
Apr 1, 2005
6
CH
Hi,

Is there a way (function) to get the parents (or immediate parent) of a child tag?

e.g.:

<div>
<p id="para">
A simple example
</p>
</div>

How does one get the "div" tag when only the "p" tag is identifiable either via "id" or index?

i.e. is there a function like:

getParentOfChild(document.getElementById("para"))

in JavaScript?


Many thanks in advance

Protonman

 
[tt]var oparent=document.getElementById("para").parentNode;[/tt]
 
If there ends up being more layers between <p> and <div>, you can use this function to walk up the hierarchy...

Code:
function getParentTag(obj, tagName){
	while(obj !=null && obj.tagName.toLowerCase()!=tagName.toLowerCase()) obj = obj.parentNode;
	return obj;
}

Adam
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top