views:

131

answers:

3

You know the drill... say you have a list of links and corresponding divs. You want to show the div when the link is clicked -- so you want to get a reference to the div so you can hook an event up on the link.

When you're setting up your events, is it better to hook things up using unique ids like:

<a href="#" id="link123">Foo</a>
...
<div style="display: none;" id="div123"/>

or, to use some sort of parent.childnodes "relative path" to walk the DOM and get the proper reference to the div from the a?

Assume, for the purpose of this example, that the target div is a few levels removed in DOM from the link. Javascript libraries are totally kosher for this, YUI especially (but all are welcome).

+3  A: 

Your first suggestion seems to be easiest. If you're dynamically generating the pages then you can easily ensure that all your pairs match.

Why not do something like this:

<a href="#div123">Foo</a>
...
<div style="display: none;" id="div123"/>

So that it'll degrade more gracefully?

If you need more convincing about your original question, DOM traversal operations tend to be more expensive (computationally) than a simple getElementById().

Hope this helps.

Tom Wright
+2  A: 

If your links and tab panes are in the same order a simple approach is to find the pane whose index matches that of the activated link, with respect to the elements' parent nodes. This can be accomplished easily with a bit of jQuery:

<div id='nav'>
  <a href='#'>Tab 1</a>
  <a href='#'>Tab 2</a>
  <a href='#'>Tab 3</a>
</div>

...

<div id='tabs'>
  <div>Contents of tab 1</div>
  <div>Contents of tab 2</div>
  <div>Contents of tab 3</div>
</div>

...

<script type='text/javascript'>
  $(function() {
    var $nav = $('#nav a'), $tabs = $('#tabs > div');
    $tabs.gt(0).hide();
    $nav.click(function() {
      $tabs.hide().eq($nav.index(this)).show();
      return false;
    });
  });
</script>
jaz303
+1  A: 

I like to use in-line anchor tags for this, it has the added benefit of working pretty well if JavaScript and CSS are turned off.

<a href="#div-123">Foo</a>
<a href="#div-124">Bar</a>
<a href="#div-125">Baz</a>

<style type="text/css">
#hiddenDivs div {
    display: none;
}
</style>

<div id="hiddenDivs">
    <div>
     <a name="div-123"></a>
     Some stuff in here for Foo
    </div>

    <div>
     <a name="div-124"></a>
     Some stuff in here for Bar
    </div>
    <div>
     <a name="div-125"></a>
     Some stuff in here for Baz
    </div>
</div>

<script type="text/javascript">
jQuery("a[href~='#div-']").click(function(){
    // extract the name of the anchor
    var id = $(this).attr('href').split('#')[1];
    jQuery('#hiddenDivs div').hide();
    jQuery('div:has(a[name='+id+'])').show();
    return false;
})
</script>
artlung