user3541631
user3541631

Reputation: 4008

Acquring a DOM element attributes without querying again the DOM and set also a default value if doesn't exist

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

Answers (1)

nicholaswmin
nicholaswmin

Reputation: 22949

Here's what you can do:

  • Structure your attribute names and default values as k/v pairs.
  • Array.map over the Object.keys of the attribute/default pairs.
  • If the key doesn't exist as attribute, set it with it's default value.
  • Return the existing or set attribute.

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

Related Questions