Paul wrote:
Hi libsfan01,
I am inferring from your question that you are looking for the first
parent tag that is a div.
Please reply below a trimmed quote of what you are replying too.
Lets see if this gives what you are looking for:
function showRef(formElement){
var parentDiv = findParentDiv(formElement);
if(parentDiv){
alert("found: " + parentDiv.id);
}else{
alert("unable to locate parent div");
}
}
function findParentDiv(elem){
var parent = elem.parentNode;
if(parent && parent.tagName.toUpperCase()!="DIV"){
A more widely suggested method is to compare with lower case, though in
practice I guess it's a moot point. That will return the first div that
is encountered ascending the DOM tree, which may not be the first one
below the FORM coming down the tree.
The version below will stop once it reaches a form element and will
return the last div that was encountered only if it stopped at a form:
function getDiv(elem){
var div = undefined;
while (elem.parentNode && elem.tagName.toLowerCase()!="form"){
if (elem.tagName.toLowerCase() == "div") div = elem;
elem = elem.parentNode;
}
return elem.tagName
&& elem.tagName.toLowerCase() == "form"
&& div;
}
parent = findParentDiv(parent);
}
return parent;
}
Another method, where 'el' is a reference to a form control, is:
function getDiv(el){
return el.form && el.form.getElementsByTagName('div')[0];
}
Which will return:
- the first div in the DOM tree below the form element if there
is one, whether el is a child of that div or not
- 'null' if there is no div decendent of the form
- 'null' if 'el'isn't a form control (i.e. doesn't have a 'form'
property).
That may suit the OP... or not. e.g.
<script type="text/javascript">
function getDiv(el){
return el.form && el.form.getElementsByTagName('div')[0];
}
</script>
<form action="" style="border: 1px solid red; width: 10em;">
<div style="border: 1px solid green">
<input type="button" value="In a DIV"
onclick="alert(getDiv(this));">
</div>
<p style="border: 1px solid blue">
<input type="button" value="In a P"
onclick="alert(getDiv(this));">
</p>
</form>
<input type="button" value="Not in form"
onclick="alert(getDiv(this));">
--
Rob