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

4
  • 2
    What is the array of? jQuery objects? DOMElements? Commented Jan 7, 2020 at 15:20
  • @VLAZ DOM Elements Commented Jan 7, 2020 at 15:22
  • Please provide a reproducible example? stackoverflow.com/help/minimal-reproducible-example Commented Jan 7, 2020 at 15:28
  • array some expects a function Commented Jan 7, 2020 at 15:45

1 Answer 1

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
Sign up to request clarification or add additional context in comments.

4 Comments

Thank you, what do I have to change if it will be jQuery objects?
If array is a jQuery object, array.filter('[data-attr]').length is one approach @jay_dtr
Quick side note for the OP - just remember some only ensures that at least one element has that attribute, every requires that all elements do.
@jay_dtr added an approach for jQuery objects.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.