Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
243 views
in Technique[技术] by (71.8m points)

dom - Get an element by index in jQuery

I have an unordered list and the index of an li tag in that list. I have to get the li element by using that index and change its background color. Is this possible without looping the entire list? I mean, is there any method that could achieve this functionality?

Here is my code, which I believe would work...

<script type="text/javascript">
  var index = 3;
</script>

<ul>
    <li>India</li>
    <li>Indonesia</li>
    <li>China</li>
    <li>United States</li>
    <li>United Kingdom</li>
</ul>

<script type="text/javascript">
  // I want to change bgColor of selected li element
  $('ul li')[index].css({'background-color':'#343434'});

  // Or, I have seen a function in jQuery doc, which gives nothing to me
  $('ul li').get(index).css({'background-color':'#343434'});
</script>
Question&Answers:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
$(...)[index]      // gives you the DOM element at index
$(...).get(index)  // gives you the DOM element at index
$(...).eq(index)   // gives you the jQuery object of element at index

DOM objects don't have css function, use the last...

$('ul li').eq(index).css({'background-color':'#343434'});

docs:

.get(index) Returns: Element

.eq(index) Returns: jQuery


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...