I’m struggling with some jQuery code I’m working on, and I’ve narrowed down the problem to this simple example that doesn’t behave as I would expect it too:
jsFiddle:
http://jsfiddle.net/HypYT/
HTML
<div id="a">a: <span>A</span></div>
<div id="b">b: <span>B</span></div>
jQuery
jQuery.each( ["#a", "#b"], function(){
alert(this); // alerts "#a" and "#b"
$(this).hide(); //not working
$('#b').hide(); //working
});
Anyone have any insight what’s going on here?
If a function is called on a string (or other primitive),
thisbecomes a boxed object.typeof thiswill therefore return"object", not"string".This breaks jQuery. (no pun intended)
You can fix this by forcing it back to a string primitive:
You can fix this for arbitrary primitives by writing
However, using the second argument passed to
.each()will be faster, because it will avoid boxing in the first place.