Reputation: 4008
I get a DOM element using:
a = document.querySelector('[data-time]');
I want to check if the element has some other specific attributes.
If they have I want to get their value or set a default value.
I can use:
c = a.querySelector('[data-time-pre])
but I call for each attribute the DOM.
So I thought of using:
placeholder = a.attributes.placeholder
So, in this case what is the simplest way to allocate a default value if the attribute doesn't exist.
I found hasOwnProperty('property1')
but I'm not sure the attribute I'm looking for are inherited, plus I need to use multiple ifs
if I have many attributes.
Maybe there is something like:
placeholder = (a.attributes.placeholder, 'default')
Upvotes: 0
Views: 77
Reputation: 22949
Here's what you can do:
Array.map
over the Object.keys
of the attribute/default pairs.const el = document.querySelector('#el')
const attrs = {
// key : default value
['data-foo']: 'foo',
['data-bar']: 'bar',
['data-baz']: 'baz'
}
const results = Object.keys(attrs).map(key => {
if (!el.hasAttribute(key))
el.setAttribute(key, attrs[key])
return { attr: key, value: el.getAttribute(key) }
})
console.log(results)
<div id="el" data-foo="hello-world"></div>
Upvotes: 2