[thelist] Navigating the DOM

Kasimir K evolt at kasimir-k.fi
Mon Apr 4 02:59:02 CDT 2005


Noah St.Amand scribeva in 2005-04-04 04:13:
> Is it possible to refer to an element that doesn't have an id? To be 
> specific, given this HTML:
> 
> <div id="shortcuts">
>    <div class="block block-menu" id="block-menu-36">
>      <h3>Shortcuts</h3>
>      <div class="menu">
>        <ul>
>          <li class="expanded"><a href="residents" title="">Residents</a>
>            <ul>
> 
> Is there anyway to do this in the javascript:
> 
> var menu = "the last ul in the example above"
> var actuator = "the a after <li class="expanded"> in the example above"

It's bit unclear what to do here, as the example above is incomplete - 
are there further <ul> elements further down, and do we want the first 
or last <a> element? The <a> above is both first and last...

Here's a quick example how to go about with this - untested and all but 
could give you an idea:

function getDeepestUl(startEl) {
    var uls = startEl.getElementsByTagName('ul');
    var last = 0;

    for (var i = 0; i < uls.length; i++) {
       if (!uls[i].getElementsByTagName('ul')) {
          // the ul that has no uls as its descendants
          // is the last/deepest
          last = i;
       }
    }
    return uls[last];
}

var menu = getDeepestUl(document.getElementById('shortcuts'));

.k



More information about the thelist mailing list