A common task you might want to accomplish in jQuery is to match elements that are paired together. For example, you have a page full of authors and only want to show their biographies if they click on a link.
Your first thought might be to do something like the following:
The problem with this approach is that when you click on the <dt /> tag it will open all of the <dd /> tags. This is because the selector being used specifies all of the <dd /> tags and doesn't do anything to filter the tags to the specific matching tag.
While there are many ways to solve this problem, depending on how your DOM is structured, this method should work any time you have a DOM structure in which your paired elements appear in the same order of the DOM. This means my two selectors should return an array of elements where the positions of the paired elements match exactly. For example:
If the order of the items in the array don't match, then you won't achieve the effect your after. The trick is to use the $.each() method to loop through the results. This allows you to find the paired element and attach the event to each individual element.
I've set up a page with a working example, so make sure to exam the code behind the scenes.
Comments for this entry have been disabled.