1

I have an object array, and I want to test if one of them has a data-attr so I could make a simple if statement, here is an example of what I'm trying to do

if (array.hasAttribute("data-attr")) {}

I'm tried some() and every()

if (array.some(this.hasAttribute("data-attr"))) {}

but I can't figured out the right syntax, please help

Andrew
  • 695
  • 1
  • 8
  • 21

1 Answers1

3
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
VLAZ
  • 26,331
  • 9
  • 49
  • 67