2

I am trying to make an array from elements with a certain class in my web page. The array should get the videofile attribute value from all a tags with the class videoLink.

The final values in the array should be.

 cycling_large, ocean_medium, winecountry_part1



 <a class="videoLink"  videofile="cycling_large"  ></a>
 <a class="videoLink" videofile="ocean_medium" ></a>
 <a class="videoLink" videofile="winecountry_part1" ></a>

I tried this but, does not work.

var values = $('.videoLink').map(function() { return this.attr('videofile'); }).get();

Thanks in advance.

1
  • 1
    videofile? I think you mean data-videofile... :P Commented Nov 2, 2011 at 23:53

3 Answers 3

6
var links = document.getElementsByClassName("videoLink");
var values = [].map.call(links, function (el) {
  return el.getAttribute("videofile");
});

Because you don't jQuery for simple things.

Browser support:

Sign up to request clarification or add additional context in comments.

3 Comments

You will however, need to define the array.map prototype if you want this to support IE 8 and earlier, same with document.getElementsByClassName. See developer.mozilla.org/en/JavaScript/Reference/Global_Objects/…
@wsanville yes. But there are shims for that.
No need for slice - just [].map.call( links, function ( el ) { ...
1

Change return this.attr('videofile'); to return $(this).attr('videofile');. You need to enclose the this in $() so it becomes a jQuery object that you can then call attr() on.

Example: http://jsfiddle.net/r9xJn/

Comments

0
var result = $.map($('a.videoLink'), function(a) {
   return $(a).attr('videofile');
});

Working example: http://jsfiddle.net/hY6zM/

3 Comments

If you look at the output in Firebug, or in the IE developer toolbar, or in Chrome, you'll see console.log will print ["cycling_large", "ocean_medium", "winecountry_part1"]
How could I then store something like this in the array? video/'+ videofile +'.mp4
Change the return statement to: return 'video/' + $(a).attr('videofile') + '.mp4';

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.