[thelist] DOM Help
Peter-Paul Koch
pp.koch at gmail.com
Thu Feb 3 12:28:59 CST 2005
> Is there any way to "walk" the DOM in javascript to find a given tag's
> ancestor/parent or child tags (like you can in XSL)?
Sure.
Drawback: if you change the structure of your HTML the script won't
work any more.
> But I'd like to use this:
>
> ================
> <div>
> <h3>
> Header Text <a href="#" onclick="toggleShowHide();
> return false;">Show/Hide Description</a>
> </h3>
> <p>
> This is description to Show/Hide.
> </p>
> </div>
> =================
>
> What I'd like to do from within the script is:
>
> 1. Find the <div> tag that surrounds the <a> tag that was clicked.
> 2. Access the <p> object that lies within the same <div> tag (to change it's
> css properties).
>
First you have to set the event handler in a different way. Why?
Because with my method the this keyword works properly (see
http://www.quirksmode.org/js/this.html for an explanation)
var x = document.getElementsByTagName('a');
for (var i=0;i<x.length;i++)
{
if (x[i].parentNode.nodeName != 'H3') continue; // if the A's parent
is not an H3', ignore
x[i].onclick = showHide;
}
Now we can proceed:
function showHide()
{
var toggleElement = this.parentNode.nextSibling;
// theoretically the line above should do the trick, but...
// empty text nodes can cause problems, so continue until you find
a P element
while (toggleElement.nodeName != 'P')
toggleElement = toggleElement.nextSibling
// found the right element
// change css properties of toggleElement
}
> Is there any way navigate the DOM like this in javascript? And while I'm on
> the subject, is there a good book available on the DOM? All I can find are
> single chapters in books about javascript etc.
As far as I know there's no book that only treats the DOM.
--
-------------------------------------------------------------------
ppk, freelance web developer
Recent article: JavaScript triggers,
http://www.alistapart.com/articles/scripttriggers/
Bug Report: Report bugs yourself, or comment on previously
reported ones.
http://www.quirksmode.org/bugreports/
------------------------------------------------------------------
More information about the thelist
mailing list