user973671
user973671

Reputation: 1650

Javascript array from all elements with a certain class name

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.

Upvotes: 2

Views: 5872

Answers (3)

Raynos
Raynos

Reputation: 169451

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:

Upvotes: 6

wsanville
wsanville

Reputation: 37516

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

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

Upvotes: 0

Will
Will

Reputation: 20235

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/

Upvotes: 1

Related Questions