jQuery
New Wave Javascript
discuss » Parent problem - (I think)
Posted: Mon Feb 13 10:19:33 EST 2006
From: Jim Dabell <
jim-jquery.com at jimdabell.com
>
>
I have DL with a DD with a class of "extract", there is then another
>
DD with a sub UL and LI -like so
>
>
<dd class="extract">some text</dd>
>
<dd clas="actions">
>
<ul><li class="readextract"><a href=""></a></li>
>
>
I've hidden the extract class with $("dd.extract").hide(); in init -
>
$(document).ready(init);
>
>
I want to be able to click the link and show or hide (toggle) the
>
extract class. I'm sure it must be simple, but I can't figure it out.
The links sound nothing at all like descriptions of definitions, which is what
the DD element type is for. I'd be surprised if there wasn't a much better
choice for your markup.
Having said that, assuming the markup above, try this:
$(document).ready(function() {
$("dd.extract").hide();
$("dd.actions a").click(function(event) {
var extract = this.parentNode.parentNode.parentNode;
while (extract = extract.previousSibling) {
if (extract.className == "extract") break;
};
if (!extract) return;
$(extract).show();
event.preventDefault();
});
});
Basically, it finds the links, then adds an onclick event handler that walks
up the DOM and then backwards until it finds the extract, then shows it.
Making it into a toggle from that point is easy.
In case you are wondering why you don't use extract.previousSibling
immediately, it's because, depending on the way you lay out your HTML, the
previousSibling could be a textNode containing just linebreaks and tabs.
You shouldn't be including the toggle link in your HTML at all, you should be
adding it into your page with Javascript. That way, people with Javascript
unavailable don't get broken links that do nothing.
--
Jim