Marc P
Marc P

Reputation: 586

How to jquery to get elements and store in array for later use?

I'm trying to gather a specific set of <li> elements that I'd like to use later in a loop. However, I don't seem to have the right syntax down: the debug console tells me that my object is undefined. Can someone tell me what I'm doing wrong?

var all_help_triggers = [];
$(".canned-triggers > li").each(function() { all_help_triggers.push($(this)) });
all_help_triggers[0].click(function(){alert('hi!');})

Upvotes: 1

Views: 1664

Answers (3)

Mortalus
Mortalus

Reputation: 10712

When you use each() the "this" value refers to "each" element it iterates. so instead using an additional array, you should try something like that ...

$(".canned-triggers > li").each(function() { 
    $(this).click(function( {
       alert('hi!')
    });
});

Just noticed your comment:

see Fiddle example: http://jsfiddle.net/ScRqc/

<ul class="canned-triggers">
    <li data-element="#li1">heyo1</li>
    <li data-element="#li2">heyo2</li>
    <li data-element="#li3">heyo3</li>
</ul>

<ul class="canned-content">
    <li id="li1">I'm heyo content 1</li>
    <li id="li1">I'm heyo content 2</li>
    <li id="li2">I'm heyo content 3</li>
</ul>


$('.canned-content > li').hide();

$('.canned-triggers > li').click(function() {
    var toggleElement = $(this).data("element");
    $(toggleElement).show();
});

Upvotes: 1

Samuel Liew
Samuel Liew

Reputation: 79032

You can simply do this:

// save selected jQuery objects into variable
var all_help_triggers = $(".canned-triggers > li");

// get first element in jQuery object, and assign a click handler
all_help_triggers.eq(0).click(function(){
    alert('hi!');
});

EDIT (Based off additional comment):

To get the index, use .index()

$('.canned-content > li').hide();

$('.canned-triggers > li').click(function() {
    var i = $(this).index();
    $('.canned-content > li').eq(i).show();
});

http://jsfiddle.net/samliew/erp2J/11/

If you want to hide a list on page load, you should do it in CSS. Instead of:

$('.canned-content > li').hide();

remove that line and add this CSS instead:

.canned-content > li { display: none; }

Upvotes: 3

gustavohenke
gustavohenke

Reputation: 41440

You should check whether your selector does return anything.

Also, an jQuery collection is array-like, what means you don't need to explicitly convert it to an array... you can loop thru it with an for without any problems.

However, if you still need an JavaScript array, you can do so with the following code:

var all_help_triggers = $.makeArray( $(".canned-triggers > li") );

More docs on the $.makeArray method here

Upvotes: -1

Related Questions