如何检查DOM元素和/或属性是否有效? [英] How to check if DOM element and/or attribute is valid?

查看:76
本文介绍了如何检查DOM元素和/或属性是否有效?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一系列元素:

var elements = ['div','a','p','foo']

我还有一系列属性:

var attributes = ['src','href','quux ','id']

我想了解如何验证上述组合是否会构成有效的DOM对象。

或者换句话说:

如何根据DOM模式验证DOM对象? *

例如(基于以上元素和属性):

For example (based on the above elements and attributes):

DOM_result = '<div src />';  // = false
DOM_result = '<div href />'; // = false
DOM_result = '<div quux />'; // = false
DOM_result = '<div id />';   // = true
DOM_result = '<a src />';    // = false
DOM_result = '<a href />';   // = true
DOM_result = '<a quux />';   // = false
DOM_result = '<a id />';     // = true
etc...

* =不确定是否调用 DOM模式

* = not sure if this is called DOM schema.

PS:

在我的例子中我使用JS,但请考虑这个问题脚本语言不可知。

PS:
In my example I'm using JS, but please consider this question scripting language agnostic.

推荐答案

大多数内容属性都是

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.

这篇关于如何检查DOM元素和/或属性是否有效?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆