I would like to get the third or forth element and set its id.
I found that:
$('#menu li:first').attr('id', 'test')
its actually working but I only get the first element. On the other hand I tried to use the following but it is not working.
$('#menu li').get(0).attr('id', 'test')
Can someone explain how to get the desirable element? (eg 4 or 5) and set its id and why the second bunch of code it's not working?
I would like to get the third or forth element and set its id.
I found that:
$('#menu li:first').attr('id', 'test')
its actually working but I only get the first element. On the other hand I tried to use the following but it is not working.
$('#menu li').get(0).attr('id', 'test')
Can someone explain how to get the desirable element? (eg 4 or 5) and set its id and why the second bunch of code it's not working?
Share Improve this question asked May 8, 2012 at 17:15 glarkouglarkou 7,10112 gold badges69 silver badges122 bronze badges 2-
The
.get()
function returns the DOM element itself, rather than a jQuery object that contains the DOM element, so you can't call jQuery functions (such as.attr()
) on it. As the answers have already pointed out, the.eq()
function is intended for that. – Anthony Grist Commented May 8, 2012 at 17:19 -
For the record, both of the answers below are correct, if you are curious why
get
is not giving you what you want it is because theget
function returns the nativeDOMElement
as opposed to the wrapped jQuery set. – Paolo Bergantino Commented May 8, 2012 at 17:19
5 Answers
Reset to default 5you can use eq()
method:
$('#menu li').eq(2).attr('id', 'third') // selects third element
$('#menu li').eq(3).attr('id', 'fourth') // selects fourth element
Try using .eq
function.
$('#menu li').eq(4).attr(...)
or
$('#menu li:eq(4)').attr(...)
On a side note .get(0)
return you a DOM element and not jQuery object.
$('#menu li:eq(3)').attr('id', 'id_4');
$('#menu li:eq(4)').attr('id', 'id_5');
or
$('#menu li').eq(3).attr('id', 'id_4');
$('#menu li').eq(4).attr('id', 'id_5');
eq()
or :eq()
both take a parameter index of target element and it is always
targetElementIndex - 1
. Because it is Zero based.
So, if you target 4th or 5th element then you have to gives arguments as 3 and 4.
DEMO
As mentioned in the ments, get() returns the DOM element.
It is possible to set the id of an element without using jquery's attr()
.
$('#menu li').get(3).id = 'test';
$('#menu')
selects element with the id "menu".
$('#menu li')
or
$('#menu').find('li')
selects all it's <li>
descendants and
$('#menu li').eq(3)
selects the fourth (as they are labeled from zero).
Note also that
$('#menu li')[3]
will get the HTMLElement itself, instead of its jQuery wrapper.