Search code examples
jqueryarraysarearel

Retrieve REL contents from variable number of elements and store in array


I've been trying to work out how to do this but there's just too many moving parts for my level of jQuery/JavaScript so I can't work out where I'm going wrong.

I'm simply trying to create an array from all REL attributes in a variable number of area tags:

<map name="Map">
    <area shape="rect" coords="45,13,125,107" class="lightbox" rel="/img/yachts/layouts/sml/horizon-56-aft-stateroom.jpg" href="/img/yachts/layouts/lrg/horizon-56-aft-stateroom.JPG" alt="Aft Stateroom" title="Aft Stateroom">
    <area shape="rect" coords="310,37,366,83" class="lightbox" rel="/img/yachts/layouts/sml/horizon-56-vip-cabin-2.JPG" href="/img/yachts/layouts/lrg/horizon-56-vip-cabin-2.JPG" alt="VIP Cabin" title="VIP Cabin">
    <area shape="rect" coords="126,19,207,99" class="lightbox" rel="/img/yachts/layouts/sml/horizon-56-salon.jpg" href="/img/yachts/layouts/lrg/horizon-56-salon.jpg" alt="Saloon" title="Saloon">
    <area shape="rect" coords="207,12,284,52" class="lightbox" rel="/img/yachts/layouts/sml/horizon-56-port-cabin.jpg" href="/img/yachts/layouts/lrg/horizon-56-port-cabin.jpg" alt="VIP Cabin" title="Port Cabin">
    <area shape="rect" coords="223,68,285,116" class="lightbox" rel="/img/yachts/layouts/sml/horizon-56-starbord-cabin.jpg" href="/img/yachts/layouts/lrg/horizon-56-starbord-cabin.jpg" alt="VIP Cabin" title="Starboard Cabin">
    <area shape="rect" coords="4,16,37,107" class="lightbox" rel="/img/yachts/layouts/sml/horizon-56-platform.jpg" href="/img/yachts/layouts/lrg/horizon-56-platform.jpg" alt="VIP Cabin" title="Swim Platform">
    <area shape="rect" coords="366,28,406,96"  class="lightbox" rel="/img/yachts/layouts/sml/Horizon-56-bowpad.jpg" href="/img/yachts/layouts/lrg/horizon-56-bowpad.JPG" alt="Bow" title="Bow of Horizon 56">
  </map>

My end goal is to feed this to a simple jQuery preloader to preload these images but I can handle that bit once I can get the array built!

Thanks in advance for any and all help!

Bob


Solution

  • Demo: http://jsfiddle.net/CFGb7/1/

    // create array for storing rels
    var rels = [];
    // loop through each `area` element
    // you could adjust this selector to be more specific if you like
    $('area').each(function(i, el){
        // push onto the array, each element's `rel` attribute
        rels.push($(el).attr('rel'));
    })
    // check what the array looks like now :)
    console.log(rels)
    // should log to console...
    // ["/img/yachts/layouts/sml/horizon-56-aft-stateroom.jpg", "/img/yachts/layouts/sml/horizon-56-vip-cabin-2.JPG", "/img/yachts/layouts/sml/horizon-56-salon.jpg", "/img/yachts/layouts/sml/horizon-56-port-cabin.jpg", "/img/yachts/layouts/sml/horizon-56-starbord-cabin.jpg", "/img/yachts/layouts/sml/horizon-56-platform.jpg", "/img/yachts/layouts/sml/Horizon-56-bowpad.jpg"]