views:

793

answers:

5

I have a DOM element with an ID similar to:

something[500]

which was built by my Ruby on Rails application. I need to be able to get this element via jQuery so that I can traverse my way up the DOM to delete the parent of it's parent, which has a variable ID that I don't have access to beforehand.

Does anyone know how I could go about this? The following code doesn't seem to be working:

alert($("#something["+id+"]").parent().parent().attr("id"));

Upon further inspection, the following:

$("#something["+id+"]")

returns an object, but when I run ".html()" or ".text()" on it, the result is always null or just an empty string.

Any help would be greatly appreciated.

+5  A: 

Try:

alert($("#something\\["+id+"\\]").parent().parent().attr("id"));

See Special Characters In Selectors (in the second paragraph).

karim79
special (meta) character explaination is now in the second paragraph on the page inidcated in karim79's post
Keith K
@KKirk - thanks for that.
karim79
+1  A: 

Try this:

alert($("#something\\["+id+"\\]").parent()[0].parent()[0].attr("id"));
Tim S. Van Haren
+1  A: 

Square brackets have special meaning to jQuery selectors, the attribute filters specifically.

Just escape these and it will find your element fine

$( "#something\\[" + id + "\\]" )
Peter Bailey
Thanks Paolo =)
Peter Bailey
+1  A: 

An id cannot include square brackets. It is forbidden by the spec.

Some browsers might error correct and cope, but you should fix you data instead of trying to deal with bad data.

David Dorward
Thanks for the link to the spec. I realize that they're not valid ID's, but Rails adds them for convenience sake in the controller.
Mike Trpcic
I didn't think Rails was that bad. Patch it to be sane and file the patch with a bug report :)
David Dorward
A: 

You can escape them using \\ or you could do something like this...

$(document.getElementById("something[" + id + "]"))
Josh Stodola