Selecting an element by id from a variable

Selecting an element by id from a variable

Hi All, 

I'm trying to do something which I think should be very easy, but I can't get it right, and I'm not sure why.

The basic HTML structure I have is this:

  1. <a href="" data-id="xx">Link</a>
  2. <a href="" data-id="yy">Link</a>
  3. <div id="xx">...</div>
  4. <div id="yy">...</div>

And so on.

When I click on the link with the data-id of xx I want that to toggle a class of 'open' on the div with an id of xx. Similarly for the yy link, and so on.

This is the jQuery I'm using:
  1. $(document).ready(function() {
  2.     $("a[data-id]").each(function() {
  3.         $(this).click(function(e) {
  4.             var dataId = $(this).attr("data-id");
  5.             $(dataId).toggleClass("open");
  6.             e.preventDefault();
  7.         });
  8.     });
  9. })

I know that the variable dataId is picking up the correct value of the data-id, but the class isn't being toggled on the div. Am I wrong that $(dataId) should select the appropriate div? Or am I doing something else wrong?