Toniq
Toniq

Reputation: 4996

Jquery attribute selection

I have this markup, example:

<div class="playlist-item" data-mp4="01.mp4" data-mp4-720p="02.mp4" data-mp4-1280p="03.mp4"></div>

I would like to select 'data-mp4' attributes in order they appear in html, so I end up with array like this:

[{quality: 'default', path:01.mp4}, {quality: '720p', path:02.mp4}, {quality: '1280p', path:03.mp4}]

I tried this but it appears different browsers order these attributes differently:

var track = playlist.find("div[class='playlist-item']");

$.each(track[0].attributes, function (i, e) { 
    if(/mp4/.test(e.name)){ 

    }
});

Upvotes: 0

Views: 41

Answers (2)

Guffa
Guffa

Reputation: 700152

The order of attributes in HTML is not preserved when the HTML code is parsed into elements, so you can't get the attributes in the order that they were in the HTML.

If you want the attribute values in a specific order, you have to sort them after getting them from the element.

Example:

var attr = Array.prototype.slice.call(track[0].attributes);
attr.sort(function(x, y){
  return x.name < y.name ? -1 : x.name > y.name ? 1 : 0;
});

To decide the order of attributes you can use a map to translate names to values:

var attr = Array.prototype.slice.call(track[0].attributes);
var map = { "data-mp4" : 1, "data-mp4-720p": 2, "data-mp4-1280p": 3 };
attr.sort(function(x, y){ return map[x.name] - map[y.name]; });

Upvotes: 2

James LeClair
James LeClair

Reputation: 1294

One option: accessing it by the data prop. However there's one catch to that. If you have a data prop thats data-some-prop the jquery specification states it must be called as $.data('someProp') instead of some-prop. This is a catch because it must be a string and not a number - the selector doesn't work. If you changed your properties to just be data-720p and data-1280p you could use the following:

var track = $('.playlist-item')[0]
var qualityArray = [
    {quality: 'default', path: $(track).data('mp4')},
    {quality: '720p', path: $(track).data('720p')},
    {quality: '1280p', path: $(track).data('1280p')}
]

if you want a more descriptive data name, you could use something that begins with a string like data-mp4-hd and data-mp4-fullhd to be called like $.data('mp4Hd')

Upvotes: 0

Related Questions