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:
- <a href="" data-id="xx">Link</a>
- <a href="" data-id="yy">Link</a>
- <div id="xx">...</div>
- <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:
- $(document).ready(function() {
- $("a[data-id]").each(function() {
- $(this).click(function(e) {
- var dataId = $(this).attr("data-id");
- $(dataId).toggleClass("open");
- e.preventDefault();
- });
- });
- })
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?