jQuery – eq(x) vs get(x) March 27, 2012
Posted by kevinbe71 in Javascript, jQuery, Web Development.add a comment
Even if you’ve been working with jQuery for a while you may not have realized that accessing the jQuery results by using square brackets resulted in the raw DOM object. The get() method has the same result. The way to get a single item by index, while preserving all of the jQuery goodness, is to use the eq() method.
For example, if you retrieve all the check boxes that have the “selectionlist” class using this statement: $(“.selectionlist”) and wish to access the checked property using attr(“checked”), you’ll get the following results:
- $(“.selectionlist”).get(0).attr(“checked”) – fails with error because attr is not available on the raw DOM element.
- $(“.selectionlist”)[0].attr(“checked”) – same as above for the same reason.
- $(“.selectionlist”).eq(0).attr(“checked”) – now you’ll get the desired boolean result without error.
The error that you’ll get is something like this: HTMLInputElement has no method ‘attr’
x is undefined or… text/javascript vs application/javascript vs application/x-javascript February 27, 2011
Posted by kevinbe71 in Development, IE, Javascript, Web Development.add a comment
Recently I’ve been playing around with iui and doing a webapp for the iPhone. Everything was working fine on the iPhone itself but I needed to do a little bit of debugging of the javascript while using IE and that’s when things went south…
I received an “x” is undefined error when a javascript function was being called on class “x”. It seemed as if IE just couldn’t see the javascript file that I was including in my web page but that didn’t seem right- or was it? Actually it turned out that’s exactly what was happening because IE 8 and earlier do not adhere to the newer RFC 4329 spec. My web page was using type=”application/x-javascript” (not even the standard application/javascript). While mobile Safari was happy with this, IE was not.
The only reason that I managed to figure this one out (a Google search didn’t yield the right answer because the recommendations I found said that “application/javascript” was what I should be using!) was that my page had two javascript references by chance, one using “text/javascript” and one using “application/x-javascript”. When I fired up the IE debugger it showed the contents for the “text/javascript” file but the “application/x-javascript” file showed up blank. I looked into what the differences were and found this out.
Anyway, just thought I’d post this here in case anyone else has run into this one… You must use text/javascript if you want your javascript to work in IE as well as other browsers even if it has been deprecated! Maybe IE 9 will fix this? Not sure, don’t have it installed…