3

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.

run
  • 543
  • 4
  • 8
  • 20

4 Answers4

7

You probably want to use eq for this:

 alert($('img').eq(0).attr('alt'));
Elliot Bonneville
  • 51,872
  • 23
  • 96
  • 123
7

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)

Andreas Wong
  • 59,630
  • 19
  • 106
  • 123
2

$("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.

Kyle Trauberman
  • 25,414
  • 13
  • 85
  • 121
1

$('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').

xdazz
  • 158,678
  • 38
  • 247
  • 274