harryajh said:
Is it possible in JavaScript to to get the ancestor element of the <a>
element below that has an id beginning with 'panel'
<div id='panel1'>
<div>
<a href="#" onclick="closeDiv(getPanel());">Close</a>
</div>
</div>
The idea being is that the getPanel() returns the 'panel' element &
passes it as a parameter to the closeDiv() function without having to
explicitly specify 'panel1', 'panel2' etc...
I am trying to learn how to navigate the DOM but this has me stumped!
While traversing the document tree upwards with a loop is a good idea
(although it should be done better than suggested in this thread, see
previous discussions), XPath can provide the correct answer more efficiently
than that. I have tested the following in Firefox 2.0.0.11 and Firebug to work:
/*
* This part works in Mozilla only; we need a Document object for this
* example
*/
/*
* E4X syntax, works in Firefox 1.5+ only; use strings/Array in other
* versions/UAs
*/
var s = <div id='panel1'>
<div>
<a href="#" onclick="closeDiv(getPanel());">Close</a>
</div>
</div>;
var p = new DOMParser();
var d = p.parseFromString(s, "application/xhtml+xml");
/*
* try..catch is not universally supported, see previous discussions;
* this is to handle possible XPath errors
*/
try
{
// Example: traversing downwards the document tree
// W3C DOM Level 3 XPath only; see MSDN2 Library for XPath in MSXML
var child = d.evaluate(
'//*[@id="panel1"]/div/a',
d.documentElement,
null,
XPathResult.FIRST_ORDERED_NODE_TYPE,
null
).singleNodeValue;
/*
* console.log() in Firebug (Lite) only; you may want to write
* a wrapper for other environments, see previous discussions.
*/
console.log(child);
// Example: traversing upwards the document tree
var ancestor = d.evaluate(
'ancestor::div[@id="panel1"]',
child,
null,
XPathResult.FIRST_ORDERED_NODE_TYPE,
null
).singleNodeValue;
console.log(ancestor);
}
catch (e)
{
e
}
See
http://developer.mozilla.org/en/docs/XPath pp. and
http://www.w3.org/TR/DOM-Level-3-XPath/ pp. for details.
Another possibility is probably using implemented interfaces of W3C DOM
Level 2 Traversal and Range:
http://www.w3.org/TR/2000/REC-DOM-Level-2-Traversal-Range-20001113/traversal.html
As for the child node object reference in this example, you can always pass
`this' in the event handler attribute value:
<a href="#" onclick="closeDiv(getPanel(this));">Close</a>
That said, avoid `a' elements like the above; they won't work without script
support, and may cause navigation to the top of the document. See the FAQ
for details.
HTH
PointedEars