getElementsByName on jQuery

carmelo arena picture carmelo arena · Jun 26, 2012 · Viewed 7.3k times · Source

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()

Answer

Jezen Thomas picture Jezen Thomas · Jun 26, 2012

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.