How to check if DOM element and/or attribute is valid?

后端 未结 1 1834
孤街浪徒
孤街浪徒 2021-01-18 13:10

I have an array of elements:
var elements = [\'div\', \'a\', \'p\', \'foo\']

I also have an array of attributes:
var attributes = [\'src\'

1条回答
  •  挽巷
    挽巷 (楼主)
    2021-01-18 13:35

    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.

    0 讨论(0)
提交回复
热议问题