This is 2 test Jquer...">

Why does $ ("img") [0] not work?

the 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 no popup and shows This is 1 test.

+3
source share
4 answers

To directly answer your question:

This does not work because it [0]returns a native selector DOM element that does not have a method called .attr(). You need to use .eq(index)one that basically extracts the indexth element from the elements represented $(). Note that it $()returns an object that looks like an array, not a per-se array (therefore it [0]does not work out of the box)

+7
source

You probably want to use eqfor this:

 alert($('img').eq(0).attr('alt'));
+7
source

$("img")[0] DOM. , jQuery DOM.

$("img").eq(0), jQuery.

+2

$('img')[0]returns an HTMLElement object, not a jquery object, so it has no method .attr. If you want to use it, you must do it $('img')[0].getAttribute('alt').

Or you still want a jquery object you can use $('img').first().attr('alt').

+1
source

All Articles