array.some(this.hasAttribute("data-attr"))
Was almost correct. Array#some
takes a predicate, so you need to do
array.some(function(el) {
return el.hasAttribute("data-attr");
})
Or shorter using arrow functions:
array.some(el => el.hasAttribute("data-attr"))
Array#every
works the same way and takes a predicate, so you can call it the same way:
array.every(function(el) {
return el.hasAttribute("data-attr");
})
//or
array.every(el => el.hasAttribute("data-attr"))
And if you want to use one or the other, you can extract the predicate and re-use it:
var hasDataAttribute = el => el.hasAttribute("data-attr")
array.some(hasDataAttribute)
array.every(hasDataAttribute)
If you have jQuery objects, you have to use some tricks since jQuery doesn't have a method that returns true
or false
for the existence attributes. You can easily simulate it with obj.attr('some-attribute') !== undefined
- this will return true
if some-attribute
exists and false
if it doesn't.
var hasDataAttribute = jQueryEl => jQueryEl.attr('data-attr') !== undefined
For data-*
attriutes, you can also use jQuery.data()
which is (in this case) a shorthand element.attr('data-something')
is the same as element.data('something')
:
var hasDataAttribute = jQueryEl => jQueryEl.data('attr') !== undefined