JQuery - $('#test ul > li').index(2).hide(); - possible?
Asked Answered
H

4

8

Can I work with the index value so easily? I think using the natural index values is better then using classes. I want to use the .index in that way.

Html

<div id="test">
<ul>
<li>Im index 0</li>
<li>Im index 1</li>
<li>Im index 2</li>
<li>Im index 3</li>
</ul>
</div>

Pseudo (Jquery) Javascript

$('#test ul > li').index(2).hide();

$('#test ul > li').index(1).click(function() {
 alert('lulz you clicked the li with the index value of 1 bro');
});

I doesnt find a clue how to work this way with the .index value.. is it possible to work that easily with this method??

Hennie answered 4/1, 2011 at 8:29 Comment(0)
D
12

You can use eq:

$('#test ul > li').eq(2).hide();

It can also be a part of your selector:

$('#test ul > li:eq(2)').hide();

If you want the third li in all uls in #test, you can use nth-child (note it is 1-based):

$('#test ul > li:nth-child(3)').hide();
Dorsman answered 4/1, 2011 at 8:35 Comment(0)
H
5

Yes you can. You want .eq() however, instead of .index():

$('#test ul > li').eq(2).hide();

Or as part of the selector:

$('#test ul > li:eq(2)').hide();
Heterosexual answered 4/1, 2011 at 8:35 Comment(0)
H
1

You're using it with an integer (number), but you can only use it with a selector or element. here

Edit:
You could write your own function like this:

function indexValue(index)
{
    $(element).each(function(key, val) {
        if(key+1 == index) // + 1 because you started from 0
        {
            return val;
        }
    });
}
Hedgcock answered 4/1, 2011 at 8:33 Comment(0)
M
0
$(document).ready(function(){
  $("button#1").click(function(){
    $("p").hide();
  });
});
$(document).ready(function(){
  $("button#2").click(function(){
    $("p").show();
  });
});
<button id="1">Clica-me</button>
<button id="2">Volta-me</button>
Malaguena answered 28/12, 2012 at 16:34 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.