carmelo arena
carmelo arena

Reputation: 561

getElementsByName on jQuery

When I select an element by name in Javascript, I usually use this code:

document.GetElementsByName('pencil')[0]

This way, it gets the first element by the name "pencil" and, if I want to get the second, third, etc. I just change the zero with one, and so on.

Now I am trying to do this in jQuery, by using this selector:

$('div[name|="pencil"]')

obviously this will be an array of divs named "pencil".

How can I make it refer to a particular name as I do with plain javascript? Thank you.


I am trying to get its innerHTML by using this code:

alert( $('div[name|="ball"]').html()

Upvotes: 1

Views: 7846

Answers (2)

Jezen Thomas
Jezen Thomas

Reputation: 13800

I would use the .eq() method and do it this way:

$('div[name="pencil"]').eq(0)

I think it reads a little easier.

I'm not sure why you're using the pipe. That would select divs with name="pencil" or name="pencil-".

Future readers: You shouldn’t be giving div elements name attributes anyway; form elements are normally given names, and they should be unique.

Upvotes: 4

user1432124
user1432124

Reputation:

$('div[name|="pencil"]')[0]

or

$('div[name|="pencil"]:first')

or

$('div[name|="pencil"]:eq(0)')

Upvotes: 3

Related Questions