views:

896

answers:

7

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

$("#imgThumbnail")

theoretically making something like this possible:

$("#imgThumbnail").src;

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

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

Do I really need to reference by the index of the array every time I am trying to reference something by ID (i.e., var oObj = $("#someobjectid")[0]; )?

+5  A: 

You should get the src attribute to get the value

$("#imgThumbnail").attr('src');
MacAnthony
+2  A: 

$(specifier) will return a collection, so yes if you want to call something on an individual member you need to pick which one. In most cases though there is a collection operator you can use to achieve the same result. For instance, you could call $('#imgThumbnail').attr('src', 'value')

Frank Schwieterman
A: 

I don't think you should be using .src with jQuery.

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

(this will read the src attribute, you set it with a second arg if you like)

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

Eli
A: 

to set the src attribute use

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

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

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

It will modify all the image src attributes on the page. Hence the $ function returns an array.

And you do not need to reference it specifically.

Virat Kadaru
+4  A: 

This post explains what the $ function returns and various ways to use it.


$(selector)

Returns a jQuery object, which could contain a number of DOM elements.


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

Returns the first result as an actual DOM element.


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

Returns the DOM element wrapped in a jQuery object so that we can do stuff like:

$(selector).eq(0).addClass("deleted").fadeOut();
SolutionYogi
+1  A: 

You should bear in mind that it's not really an array, it's a jQuery object which, among other things, allows array-style access

Gareth
+1  A: 
$(whatever)

returns the jQuery object. On the jQuery object you can do jQuery and jQuery plugin things, eg. .text() to return the text inside the element or .css("background", "pink") to make the element(s) pink.

Since src isn't a jQuery thing you cannot access it. src is however both a HTML attribute, and you can access those with the attr method:

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

src is also a DOM-property and you can access DOM-properties using [index] or by iterating through the jQuery object with each:

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