I have a problem to get DOM element's attributes in JS. Here is code:
return elem.getAttribute(attr) || elem[attr] || "";
elem.getAttribute(attr)
is used to get attributes like name
or id
, elem[attr]
is used to get attribute like tagName
. It works fine, until style
came out.
In my case, I want to have ""
when style
attribute not set. But with above code, it will try elem[attr]
when elem.getAttribute(attr)
returns null. So if style
is not set, I get all browser supported styles instead of ""
.
How to deal with this problem? Is there any better way than enum attributes?
Edit:
I want to write a general function to get element's attributes (such as name
, style
) or properties(such as tagName
).