最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to use jquery selectors to get the third or fourth element and set its id - Stack Overflow

programmeradmin3浏览0评论

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 the get function returns the native DOMElement as opposed to the wrapped jQuery set. – Paolo Bergantino Commented May 8, 2012 at 17:19
Add a ment  | 

5 Answers 5

Reset to default 5

you 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.

发布评论

评论列表(0)

  1. 暂无评论