dynamically building an array from DOM elements
There's no way this should be as hard as I am finding it.
I want to dynamically build an array like this:
- var myPlayList = [
- {name:"Title1",mp3:"path/to/title1.mp3"},
- {name:"Title2",mp3:"path/to/title2.mp3"},
- {name:"Title3",mp3:"path/to/title2.mp3"},
- ];
but I want to be able to pull the data from an unordered list in the DOM that looks like this:
- <ul id="tracklisting">
- <li><a href="path/to/title1.mp3">Title1</a></li>
- <li><a href="path/to/title2.mp3">Title2</a></li>
- <li><a href="path/to/title3.mp3">Title3</a></li>
- </ul>
Should be simple enough, right? But I've done very little dynamic building of arrays before, and I can't seem to make it work. After lots of web searches and reading up on Arrays, I am stumped.
I tried a lot of things... they all start with:
- var myPlayList = [];
And then I continue; each of these seemed logical (and yes, I tried numerous other variations)... still no luck.
- $('ul#tracklisting li a').each(function(){
- myPlayList.push('{name:"'+$(this).text()+'",mp3:"'+$(this).attr("href")+'"}');
- });
with this one (above), each item came back 'undefined', even though I could log both $(this).text() and $(this).attr("href") and see the expected result in the console.
- $('ul#tracklisting li a').each(function(i){
- myPlayList[i][name].push($(this).text());
- myPlayList[i][mp3].push($(this).attr("href"));
- });
with this one (above), I got a javascript error in Firebug console, saying that myPlayList[i] was undefined.
Obviously, there is some fundamental way of doing this that is escaping me. Who can point me in the right direction?
Thanks in advance.