javascript - How to check if DOM element andor attribute is valid? - Stack Overflow

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

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 can validate if the binations of the above would make a valid DOM object.
Or, in other words:
How can I validate a DOM object against the DOM schema?*

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...

* = not sure if this is called DOM schema.

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

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 can validate if the binations of the above would make a valid DOM object.
Or, in other words:
How can I validate a DOM object against the DOM schema?*

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...

* = not sure if this is called DOM schema.

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

Share Improve this question edited Nov 7, 2015 at 16:51 Danny Fardy Jhonston Bermúdez 5,5815 gold badges26 silver badges38 bronze badges asked Nov 7, 2015 at 15:59 Bob van LuijtBob van Luijt 7,59815 gold badges62 silver badges107 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 9

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 case-sensitive, and some have different names than content attributes, e.g. you should check className instead of class.

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1742304445a4418654.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信