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.
Square brackets have special meaning to jQuery selectors, the attribute filters specifically.
Just escape these and it will find your element fine
Try this:
You need to escape the square brackets so that they are not counted as attribute selectors. Try this:
See Special Characters In Selectors, specifically the second paragraph:
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.
You can also do
You can escape them using
\\
or you could do something like this...