有没有办法让 JS 导出所有可能的标准 HTML 标签的列表?
例如,如果我们想获取所有可用的样式属性,我们可以
var d = document.createElement('div');
for(var property in d.style) console.log(property); // would print out all properties;
Run Code Online (Sandbox Code Playgroud)
但我们想知道是否有办法获取所有可用的 HTML 标签。
如果这样的事情不可能,有人知道我们在哪里可以获得这样的清单吗?我们无法在逗号分隔/json 中找到它...我们发现的只是带有引用等的网站...
document.querySelectorAll('*')哪个会给我们 DOM 中的所有元素。我们正在寻找所有可能的标准 HTML 标签不存在“所有可能的”HTML 标记的列表,因为可能存在无限数量的 HTML标记。有规范,其中列出了所有当前标准 HTML 标签,但当然,您可以创建自定义元素使用自己的标签
出于好奇,我查看了从规范的网页获取该列表有多难。我想出了这个:
[...document.querySelectorAll("th > code[id*='elements-3:'] > a")].map(a => a.textContent).join()
Run Code Online (Sandbox Code Playgroud)
所以,并不难。
如果您在从上面的链接打开规范时在控制台中运行该程序,截至 2018 年 10 月撰写本文(以及五年后的此编辑),它会列出 112 个元素:
a,缩写,地址,区域,文章,旁白,音频,b,基础,bdi,bdo,块引用,正文,br,按钮,画布,标题,引用,代码,col,colgroup,数据,数据列表,dd,del,详细信息,dfn,对话框,div,dl,dt,em,嵌入,字段集,figcaption,图,页脚,表单,h1,h2,h3,h4,h5,h6,头,标题,hgroup,hr,html,i, iframe,img,input,ins,kbd,label,legend,li,link,main,map,mark,menu,meta,meter,nav,noscript,object,ol,optgroup,option,output,p,param,图片,前,进度,q,rp,rt,ruby,s,samp,脚本,部分,选择,插槽,小,源,跨度,强,样式,子,摘要,sup,表,tbody,td,模板,文本区域, tfoot,th,thead,时间,标题,tr,轨道,u,ul,var,视频,wbr
使用基于代码的方法很诱人,通过检查以下属性来查找 HTML 元素构造函数window:
[...document.querySelectorAll("th > code[id*='elements-3:'] > a")].map(a => a.textContent).join()
Run Code Online (Sandbox Code Playgroud)
a,abbr,address,area,article,aside,audio,b,base,bdi,bdo,blockquote,body,br,button,canvas,caption,cite,code,col,colgroup,data,datalist,dd,del,details,dfn,dialog,div,dl,dt,em,embed,fieldset,figcaption,figure,footer,form,h1,h2,h3,h4,h5,h6,head,header,hgroup,hr,html,i,iframe,img,input,ins,kbd,label,legend,li,link,main,map,mark,menu,meta,meter,nav,noscript,object,ol,optgroup,option,output,p,param,picture,pre,progress,q,rp,rt,ruby,s,samp,script,section,select,slot,small,source,span,strong,style,sub,summary,sup,table,tbody,td,template,textarea,tfoot,th,thead,time,title,tr,track,u,ul,var,video,wbr
但:
tbody、tfoot和thead全部使用HTMLTableSectionElement,所以这意味着tablesection,但这不是标签,并且tbody, tfoot, 或theadHTMLElement实例(、、、、code... )citebaside所以,是的,代码方法不起作用。您必须从规范中获取列表。