Turning Arr[0]
into an array
The initial problem with what you're trying to do here is that Arr[0]
isn't an array. If your code was working correctly (by pulling the "small alpha" h2
element into your Arr
element at position 0), Arr[0]
would be a string.
Arr[0] === "small alpha";
Therefore, when calling Arr[0].push()
you're attempting to call an array method on a string. This throws an error:
Uncaught TypeError: Object small alpha has no method 'push'
To rectify this, we need to turn Arr[0]
into an array simply by declaring Arr[0] = []
:
...
Arr[0] = [];
Arr[0].push($(this).closest('ul').find('li').text());
...
Fixing your code
Firstly you'll want to store your h2
text into a reusable variable:
var key = $(this).closest('ul').find('h2').text();
It's well worth noting at this point that h2
elements aren't allowed to be children of ul
elements, so your HTML isn't valid in its current state. You'll need to fix this yourself and come up with a different selector, but for the remainder of this answer I'll work with what is currently there.
As we're using this as a key, we don't need to push this value into the array, so we drop the first push()
call altogether.
Rather than then using Arr[0]
to reference your key, we can instead use Arr[key]
. We now need to create your inner array and push the li
text into it:
Arr[key] = [];
Arr[key].push($(this).closest('ul').find('li').text());
Altogether, your code will now look like this:
var Arr= [];
$('a').click(function(){
var key = $(this).closest('ul').find('h2').text();
Arr[key] = [];
Arr[key].push($(this).closest('ul').find('li').text());
console.log(Arr)
});
The result of this is:
[small alpha: Array1]
--- 0: "abC"
JSFiddle demo.
Pushing each li
text into your array separately
The problem with the above code is that all of your li
values are condensed into one: Arr['small alpha'] === ["abC"]
. To fix this, we can introduce the jQuery map()
method.
Rather than calling ...find('li').text()
, we're now going to use map()
to map each li
's text into an array:
$(this).closest('ul').find('li').map(function() { return $(this).text() }).get()
Collectively your code now looks like this:
var Arr= [];
$('a').click(function(){
var key = $(this).closest('ul').find('h2').text();
Arr[key] = [];
Arr[key].push($(this).closest('ul').find('li')
.map(function() { return $(this).text() }).get());
console.log(Arr)
});
The result of this is:
[small alpha: Array1]
... 0: "a"
... 1: "b"
... 2: "C"
If you were to then click on all three "get" links, you'd end up with:
Arr
['small alpha']
['a', 'b', 'C']
['big alpha']
['A', 'B', 'C']
['number']
[1, 2, 3]