JQuery - Reference by ID - Is it supposed to return an array?

I just started using jQuery, and various sources suggest that to reference an element by ID, use the following:

$("#imgThumbnail")

theoretically, doing something like this is possible:

$("#imgThumbnail").src;

But my testing shows that something like $("#imgThumbnail")returns an array, which makes the following necessary:

$("#imgThumbnail")[0].src;

Do I need to reference an array index every time I try to reference something by ID (i.e. var oObj = $("#someobjectid")[0];)?

+5
source share
7 answers

You must get the src attribute to get the value

$("#imgThumbnail").attr('src');
+6
source

, $ .


$(selector)

jQuery, DOM.


$(selector)[0] or $(selector).get(0)

DOM.


$(selector).eq(0) or $($(selector).get(0))

DOM, jQuery, , :

$(selector).eq(0).addClass("deleted").fadeOut();
+6

$(specifier) ​​ , , - , , . , , . , $('# imgThumbnail'). Attr ('src', 'value')

+3

, , jQuery, , ,

+1
$(whatever)

jQuery. jQuery jQuery jQuery-, . .text(), .css("background", "pink"), .

src jQuery, . src, , HTML, , attr:

.attr("src")` and `.attr("src", "http://www.example.com/myimage.png")

src DOM, DOM [index] jQuery :

.each(function(){
  this.src = "http://www.example.com/myimage.png";
})
+1

, .src jQuery.

Try $("#imgThumbnail").attr('src'); 

( src, , )

: http://docs.jquery.com/Attributes/attr

0

to set the src attribute use

$("#imgThumbnail").attr("src", value)

if you use something like a class selector or tag like this

$("img").attr("src", value)

It will change all src attributes of the image on the page. Therefore, the $ function returns an array.

And you do not need to refer to it specifically.

0
source

All Articles