[thelist] DOM Help

Matt Warden mwarden at gmail.com
Thu Feb 3 11:29:12 CST 2005


Firstly, it might help to look in the archives. I have been surprised
how many times this topic has come up lately. I feel like I'm pimping
my solution to no end...

see below:

On Thu, 03 Feb 2005 10:12:19 -0700, Tony Grimes <info at scribenewmedia.com> wrote:
> 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).
> 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.

I am doing what you are trying to do using a different method. You can
see my implementation here:


Note that the only thing necessary to attach this functionality to an
element is to give it the initial class name of "collapsible" or
"expandable" (depending on the desired initial state).

I considered doing it the way you are suggesting, but I was not
familiar enough with the DOM at the time.

Basically, you would need to access parents using the parentNode
property of an element. So, in your toggleShowHide(), you would need
to do something like this:

var parentDiv = callingElement.parentNode;

Then, you'll want something like this:

var ps = parentDiv.getElementsByTagName('p');
var targetP = (ps.length ? ps[0] : null);
if (targetP != null)
    // collapse

You can also do it by walking the DOM like you suggest. You could use
the parent node and then access the children of the parent node.
However, getElementsByTagName() makes your life easier, as you won't
have to test whether the node is a tag node (and then what tag), text
node, etc.

Typical warnings about testing for the availability of methods like
getElementsByTagName apply.

Matt Warden
Miami University
Oxford, OH, USA

This email proudly and graciously contributes to entropy.

More information about the thelist mailing list