且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何检查DOM元素和/或属性是否有效?

更新时间:2023-11-27 17:05:52

大多数内容属性都是

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

这些IDL属性实现为元素继承的接口中的访问器属性(即getter和setter)。

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

注意IDL属性不区分大小写,有些名称与内容属性不同,例如你应该检查 className 而不是 class

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