2

I have a form with a bunch of text elements, some of which have a data attribute set.

I want to loop through all the elements that have that attribute, extracting the attribute.

I've created a fiddle here.

var textInputs = $(':text');
alert('found ' + textInputs.length + ' textInputs');

var datas = textInputs.find('[data-foo]');
alert('found ' + datas.length + ' datas');

I'm finding the text elements, but my selector on the data attribute is returning no elements.

Ideas would be helpful...

falsarella
  • 12,217
  • 9
  • 69
  • 115
Jeff Dege
  • 11,190
  • 22
  • 96
  • 165

2 Answers2

3

The [data-foo] selector is correct, but you should use it in a filter, instead of in a find:

var datas = textInputs.filter('[data-foo]');

See working fiddle here

falsarella
  • 12,217
  • 9
  • 69
  • 115
  • 1
    That seems to work. But I'll need to read up on the difference between find() and filter(). Thanks. – Jeff Dege Jun 26 '14 at 22:34
  • To elaborate, just using the `[data-foo]` selector would mean EVERY single DOM element would have to be checked for it, quite a tedious task. Filtering down beforehand with something that can be done with a native function (like `getElementsByTagName`) is much more performant. `$('input').filter('[data-foo]')` instead of `$('[data-foo]')`. – christian314159 Jun 26 '14 at 22:34
  • Performance wise, wouldn't $(':text[data-foo]'); be faster? Or equivalent? – Christian Bonato Jun 26 '14 at 22:54
  • @Bonatoc You are right, `$(':text[data-foo]');` is faster [(see this fiddle)](http://jsfiddle.net/x6YeT/). Additionally, there is an even more efficient way: `$('[type="text"][data-foo]');`. It is also described in the [`:text` jquery selector documentation](http://api.jquery.com/text-selector/) that the `[type="text"]` is better but don't match the `` with no type attribute. – falsarella Jun 26 '14 at 23:38
  • @JeffDege I'm glad to hear that you'll seek for further knowledge! That's the most important part. Thank you :) – falsarella Jun 26 '14 at 23:44
2

http://jsfiddle.net/qjb3V/

     var datas = $(':text[data-foo]');
Christian Bonato
  • 1,253
  • 11
  • 26