code:
<img src="image1.jpg" alt="This is 1 test.">
<img src="image2.jpg" alt="This is 2 test">
jquery code:
alert($('img')[0].attr('alt'));
why there is not pop up a box, and shows This is 1 test.
You probably want to use eq
for this:
alert($('img').eq(0).attr('alt'));
To directly answer your question:
It doesn't work because [0]
returns a native DOM Element of the selector, which doesn't have a method called .attr()
. You need to use .eq(index)
, which basically extracts out the index
'th element of the elements represented by $()
. Note that $()
returns an array-like object and not an array per-se (thus [0]
doesn't work out of the box)
$("img")[0]
returns the raw DOM element. You want the jQuery object that wraps the DOM element.
use $("img").eq(0)
to get the jQuery object.
$('img')[0]
returns HTMLElement Object, not jquery Object, so it doesn't have the method .attr
.
If you want to use it, you should do $('img')[0].getAttribute('alt')
.
Or you still want the jquery object,
You could use $('img').first().attr('alt')
.