tags:

views:

27

answers:

3

How would I go about creating an array containing each link title from the following? (Link 1, Link 2, Link 3) - I'm trying to pass this data through a load() command so it then pre-caches the results to reduce load time if the user decides to click on one of the links.. (each link calls to an api fetching data related to the title)

<ul id="links">
    <li><a href="#" title="Link 1">Link 1</li>
    <li><a href="#" title="Link 2">Link 2</li>
    <li><a href="#" title="Link 3">Link 2</li>
</ul>

My idea:

var elems = document.getElementsByTagName("#links li a"); 
var arr = jQuery.makeArray(elems);
??

But i'm not sure how to get just the title attr() of each link and send it over as an array

Thank you :D

Perhaps it's better to use each() and then have the load() within that, so it makes independent load calls recursively?

Something like this instead:

    $("#similar-artists li a").each(function() { 
                    alert("alert");  // load();
}); 
+3  A: 

You can use .map() to get the array of titles, for example:

var arr = $("#links a").map(function() { return this.title; }).get();

You can give it a try here.

Nick Craver
oh yeah this is nice, so he was too fast with accepting xD
zolex
@zolex - I think it's lack of understanding really, it was posted first as well, but that's beside the point...I want to stress doing things it a much more efficient way when possible, this eliminates a loop and a lot of unnecessary logic to get a basic DOM property.
Nick Craver
I'm still here :)
Ryan
haha there are teh same loops in map()'s intermals.. but anyway (+1) ;)
zolex
@zolex - One loop, not two :), and `.attr("tittle")` is *way* more expensive than `.title` :)
Nick Craver
well, where do you see two loops?
zolex
@zolex - `.attr()` internally you're creating an object, and to fetch based on the jQuery object itself after that...I'm not really sure how you'd argue going though `.attr()` vs `.title` would *ever* be faster really?
Nick Craver
A: 

How about just iterating over the elements and building an array of titles, like this:

var elems = $("#links li a");
var arr = [];
for (var i = 0; i < elems.length; i++)
  arr.push(elems[i].title);
casablanca
+2  A: 

a quite simple task :)

var myArray = new Array();
$('#links li a').each(function() {

  myArray.push($(this).attr('title'));
});
zolex
Why do it the long way with `.map()` is specifically for this purpose, and much more efficient?
Nick Craver
i already said, i like your answer ;)
zolex