Skip to content Skip to sidebar Skip to footer

How To Check If DOM Element And/or Attribute Is Valid?

I have an array of elements: var elements = ['div', 'a', 'p', 'foo'] I also have an array of attributes: var attributes = ['src', 'href', 'quux', 'id'] I want to understand how I c

Solution 1:

Most content attributes are reflected by an IDL attribute (a.k.a property) with the same name.

Those IDL attributes are implemented as accessor properties (i.e. getters and setters) in an interface from which the elements inherit from.

Therefore, you can create an element of the desired type and check if it has the desired property:

'src' in document.createElement('div'); // false
'src' in document.createElement('img'); // true

Note IDL attributes are not case-insensitive, and some have different names than content attributes, e.g. you should check className instead of class.


Post a Comment for "How To Check If DOM Element And/or Attribute Is Valid?"