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.
getElementById() The Document method getElementById() returns an Element object representing the element whose id property matches the specified string. Since element IDs are required to be unique if specified, they're a useful way to get access to a specific element quickly.
An id cannot include square brackets. It is forbidden by the spec.
One of the most common methods to access an element in HTML DOM is getElementById() which accesses an element based on the value of its ID attribute. The value of the ID attributes are supposed to be unique and no two elements on a single HTML page should have similar IDs.
You need to escape the square brackets so that they are not counted as attribute selectors. Try this:
alert($("#something\\["+id+"\\]").parent().parent().attr("id"));
See Special Characters In Selectors, specifically the second paragraph:
To use any of the meta-characters (such as
!"#$%&'()*+,./:;<=>?@[\]^``{|}~
) as a literal part of a name, it must be escaped with with two backslashes:\\
. For example, an element withid="foo.bar"
, can use the selector$("#foo\\.bar")
. The W3C CSS specification contains the complete set of rules regarding valid CSS selectors. Also useful is the blog entry by Mathias Bynens on CSS character escape sequences for identifiers.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With