Chris Panayotoff
Chris Panayotoff

Reputation: 1946

jQuery - select elements containing custom data

I have a couple of elements like

<p data-lang-bg="Bulgarian" data-lang-en="English" >Text</p>
<p data-lang-bg="Other bulgarian text" data-lang-en="Other english text" >Text 2</p>

I have a difficulties writing a jQuery selector, that will select all elements, who have data attributes starting with data-lang . Is it possible to write such a jQuery selector

Upvotes: 1

Views: 612

Answers (3)

Nathan
Nathan

Reputation: 11149

Use a custom selector:

$.expr[':']['data-lang'] = function (obj) {
    var data = $(obj).data();
    for (i in data) {
        if (data.hasOwnProperty(i)) {
            if (i.indexOf('lang') === 0) {
                return true;
            }
        }
    }
};

Then select them with $('p:data-lang').

Upvotes: 0

Purus
Purus

Reputation: 5799

This might help.

http://code.google.com/p/jquery-list-attributes/

(function($) {
      // duck-punching to make attr() return a map
      var _old = $.fn.attr;
      $.fn.attr = function() {
          var a, aLength, attributes,   map;
          if (this[0] && arguments.length === 0) {
                    map = {};
                    attributes = this[0].attributes;
                    aLength = attributes.length;
                    for (a = 0; a < aLength; a++) {
                              map[attributes[a].name.toLowerCase()] = attributes[a].value;
                    }
                    return map;
          } else {
                    return _old.apply(this, arguments);
          }
}
}(jQuery));

Source: http://forum.jquery.com/topic/retrieving-all-attributes-of-a-given-element-and-their-values

Upvotes: 0

Denys S&#233;guret
Denys S&#233;guret

Reputation: 382092

Here's the nearest I can propose.

Change your HTML to this structure :

<p data-lang='{"bg":"Bulgarian","en":"English"}' >Text</p>

Then use this selector :

$('[data-lang]')

For example, you can get your languages values as maps :

$('[data-lang]').each(function(){
    var localizations = $(this).data('lang'); // parses the map as JSON
    ... use the object, for example localizations['en']
});

This looks to me like the correct way to use the power of custom data attributes.

Upvotes: 1

Related Questions