jQuery selectors should be strings

Spent a good amount of time today trying to figure out why the jQuery’s toggle works on first element, but doesn’t work on the following ones.

I had this code:

function ToggleComment(id) {

$("#comments[data-id=" + id + "]").toggle({ "effect": "clip", "speed": "1000" });

}

where id is a number, and a few divs with id #comments-x.

It would toggle the first div, but not the subsequent ones.

This is the fix:

$("#comments[data-id='" + id + "']").toggle({ "effect": "clip", "speed": "1000" });

Note the ” around the id.

Leave a Reply

Your email address will not be published. Required fields are marked *