如何使用javascript枚举文档中的所有html id?

时间:2022-06-16 08:14:50

I would like to be able to use javascript to find every id (or name) for every object in an html document so that they can be printed at the bottom of the page.

我希望能够使用javascript查找html文档中每个对象的每个id(或名称),以便可以在页面底部打印它们。

To understand more fully what I'm trying to accomplish, let me explain. I build large forms from time to time for things such as property applications, rental listings, detailed medical website user registration forms and such. As I do it now, I build the form, assign the id's and names and decide which values are required and such. Then when I build the php form validation and database insert portion for the form, I've been manually going through the html and pulling out all of the id's to reference from the $_post array for the input validation and database insert. This has been very time consuming and a real pain, often laced with typing errors.

为了更全面地了解我想要完成的事情,让我解释一下。我不时为物业应用,租赁列表,详细的医疗网站用户注册表等内容构建大型表格。正如我现在所做的那样,我构建表单,分配id和名称,并决定需要哪些值等。然后当我为表单构建php表单验证和数据库插入部分时,我已经手动浏览html并从$ _post数组中提取所有id以引用输入验证和数据库插入。这非常耗费时间并且是一种真正的痛苦,通常伴随着打字错误。

The form I'm working on currently is just too big, and I'd much rather write a javascript function that I can run on my local copy of the page to list all of the id's so that I don't have to copy and paste them one by one, or write them down. I could then also use the javascript loop to event print out the php code around the id names so that I'd only have to copy the list and lightly edit out the id's I dodn't need... I hope you guys get the idea.

我目前正在处理的表单太大了,我宁愿写一个javascript函数,我可以在我的本地页面副本上运行列出所有的id,这样我就不用复制了将它们逐个粘贴,或者将它们写下来。然后我也可以使用javascript循环事件打印出围绕id名称的php代码,这样我只需要复制列表并轻轻编辑我不需要的id ...我希望你们得到的理念。

Any suggestions on how I can drop all of the id's into an array, or if there is already an array I can access and loop through (I couldn't find anything on google). Also, any suggestions for how to speed up the process of producing large forms with a work flow that generates the php or makes it quicker than my current method would be greatly appreciated!

关于我如何将所有id放入数组的任何建议,或者如果已经有一个数组我可以访问并循环(我在谷歌上找不到任何东西)。此外,任何建议如何加快生成大型表单的过程,生成PHP的工作流程或使其比我当前的方法更快将非常感谢!

8 个解决方案

#1


36  

On modern browsers you can do this via

在现代浏览器上,您可以通过此方式执

document.querySelectorAll('*[id]')

should do the job.

应该做的工作。

If you need all descendants of myElement with IDs, then do

如果你需要myElement的所有后代都带有ID,那么就做

myElement.querySelectorAll('*[id]')

If you want to be really careful to exclude <span id="">, then maybe

如果你想非常小心地排除,那么也许

document.querySelectorAll('*[id]:not([id=""])')

If compatibility with older browsers is required

如果需要与旧版浏览器兼容

var allElements = document.getElementsByTagName("*");
var allIds = [];
for (var i = 0, n = allElements.length; i < n; ++i) {
  var el = allElements[i];
  if (el.id) { allIds.push(el.id); }
}

should leave you with all the IDs in allIds.

应该留下allIds中的所有ID。

If you find you need to just enumerate the IDs under a particular form node, then you can replace document.getElementsByTagName with myFormNode.getElementsByTagName.

如果您发现只需枚举特定表单节点下的ID,则可以将document.getElementsByTagName替换为myFormNode.getElementsByTagName。

If you want to include both IDs and NAMEs, then put

如果您想同时包含ID和NAME,请填写

else if (el.name) { allIds.push(el.name); }

below the if above.

如果在上面。

#2


16  

If you're doing your development using a fairly modern browser, you can use querySelectorAll(), then use Array.prototype.forEach to iterate the collection.

如果您使用相当现代的浏览器进行开发,则可以使用querySelectorAll(),然后使用Array.prototype.forEach来迭代集合。

var ids = document.querySelectorAll('[id]');

Array.prototype.forEach.call( ids, function( el, i ) {
    // "el" is your element
    console.log( el.id ); // log the ID
});

If you want an Array of IDs, then use Array.prototype.map:

如果需要ID数组,请使用Array.prototype.map:

var arr = Array.prototype.map.call( ids, function( el, i ) {
    return el.id;
});

#3


7  

The jQuery selector $('[id]') will get all the elements with an id attribute:

jQuery选择器$('[id]')将获得具有id属性的所有元素:

$('[id]').each(function () {
    do_something(this.id);
});

Working example here: http://jsfiddle.net/RichieHindle/yzMjJ/2/

这里的工作示例:http://jsfiddle.net/RichieHindle/yzMjJ/2/

#4


7  

Get all tags with the wildcard:

使用通配符获取所有标记:

var allElements = document.getElementsByTagName('*');
for(var i = 0; i < allElements.length; i++) {
    // ensure the element has an Id that is not empty and does exist
    // and string other than empty, '', will return true
    allElements[i].id && console.log(allElements[i].id);
}

#5


5  

well, since it is a form, im sure that you want to iterate only over the form elements and not all the tags in the document ( like href , div's etc.. )

好吧,因为它是一个表单,我确定你只想迭代表单元素而不是文档中的所有标签(如href,div等等)。

for (var i=0; i < form.elements.length; i++) {
   var elementId = form.elements[i].id;
}

#6


3  

with jQuery

用jQuery

$('*').map(function() {
   return this.id || null;
}).get().join(',');

this gets all the elements in the DOM, and runs a function on each to return the id (and if undefined, returning null won't return anything. This returns a jQuery object which is then converted to a JavaScript array with get() and this is then converted to a comma-separated string of ids.

这将获取DOM中的所有元素,并在每个元素上运行一个函数来返回id(如果未定义,则返回null将不返回任何内容。这将返回一个jQuery对象,然后使用get()将其转换为JavaScript数组,然后将其转换为逗号分隔的ID字符串。

Try it on this page and you get

在这个页面上试一试就可以了

"notify-container,overlay-header,custom-header,header,portalLink,topbar,hlinks,hlinks-user,hlinks-nav,hlinks-custom,hsearch,search,hlogo,hmenus,nav-questions,nav-tags,nav-users,nav-badges,nav-unanswered,nav-askquestion,content,question-header,mainbar,question,edit-tags,link-post-7115022,close-question-7115022,flag-post-7115022,comments-7115022,add-comment-7115022,comments-link-7115022,answers,answers-header,tabs,answer-7115033,link-post-7115033,flag-post-7115033,comments-7115033,add-comment-7115033,comments-link-7115033,answer-7115042,link-post-7115042,flag-post-7115042,comments-7115042,add-comment-7115042,comments-link-7115042,answer-7115043,link-post-7115043,delete-post-7115043,flag-post-7115043,post-editor-7115043,wmd-button-bar-7115043,wmd-button-row-7115043,wmd-bold-button-7115043,wmd-italic-button-7115043,wmd-spacer1-7115043,wmd-link-button-7115043,wmd-quote-button-7115043,wmd-code-button-7115043,wmd-image-button-7115043,wmd-spacer2-7115043,wmd-olist-button-7115043,wmd-ulist-button-7115043,wmd-heading-button-7115043,wmd-hr-button-7115043,wmd-spacer3-7115043,wmd-undo-button-7115043,wmd-redo-button-7115043,wmd-help-button-7115043,wmd-input-7115043,draft-saved-7115043,communitymode-7115043,wmd-preview-7115043,fkey,author,edit-comment-7115043,edit-comment-error-7115043,submit-button-7115043,comments-7115043,add-comment-7115043,comments-link-7115043,post-form,post-editor,wmd-button-bar,wmd-input,draft-saved,communitymode,wmd-preview,fkey,author,submit-button,show-editor-button,sidebar,qinfo,adzerk2,newsletter-ad,newsletter-ad-header,newsletter-signup-container,newsletter-signup,newsletter-preview-container,newsletter-preview,h-related,feed-link,feed-link-text,prettify-lang,footer,footer-menu,footer-sites,footer-flair,svnrev,copyright"

“通知容器,覆盖头,自定义标题,标题,portalLink,顶栏,hlinks,hlinks用户,hlinks-NAV,hlinks定制,hsearch,搜索,hlogo,hmenus,NAV-问题,导航标签,导航-Users,NAV-徽章,导航,无人接听,NAV-askquestion,内容,提问头,mainbar,问题,编辑标签,链接后7115022,特写问题-7115022,旗后的7115022,评论-7115022 ,添加注释-7115022,评论链接-7115022,答案,答案头,标签,回答-7115033,链接后7115033,旗后的7115033,评论-7115033,添加注释-7115033,评论链接-7115033,回答-7115042,链接后7115042,旗后的7115042,评论-7115042,添加注释-7115042,评论链接-7115042,回答-7115043,链接后7115043,删除,后7115043 ,旗后的7115043,编辑器-7115043后,大规模杀伤性武器按钮栏-7115043,大规模杀伤性武器按钮行7115043,大规模杀伤性武器粗体按钮7115043,大规模杀伤性武器斜体按钮-7115043,大规模杀伤性武器spacer1-7115043 ,WMD链路按钮-7115043,WMD引号按钮-7115043,WMD码按钮-7115043,WMD图像按钮-7115043,WMD-spacer2-7115043,WMD-olist按钮-7115043,WMD-ulist -屁股在-7115043,大规模杀伤性武器的标题按钮-7115043,WMD-HR-按钮7115043,大规模杀伤性武器spacer3-7115043,大规模杀伤性武器撤消键-7115043,大规模杀伤性武器重做按钮-7115043,大规模杀伤性武器的帮助按钮-7115043,大规模杀伤性武器输入7115043,草稿保存-7115043,communitymode-7115043,大规模杀伤性武器预览-7115043,FKEY,作家,编辑,评论-7115043,编辑注释错误-7115043,提交按钮-7115043,评论-7115043,添加注释-7115043,评论链接-7115043,成形后,编辑器后,大规模杀伤性武器按钮栏,大规模杀伤性武器输入,草稿保存,communitymode,大规模杀伤性武器预览,FKEY,作家,提交按钮,显示─编辑键,侧边栏,QINFO,adzerk2,通讯,广告,通讯,广告标题,简报,注册容器,通讯,注册,通讯预览容器,通讯预览,H相关,饲料环节,馈链接文本,美化琅,页脚,页脚,菜单,页脚,网站,页脚,风骚,svnrev,版权”

#7


0  

A simple ES6 (es2015) solution based on answer of user113716

基于user113716的答案的简单ES6(es2015)解决方案

const elementsById = document.querySelectorAll('[id]');
const elementsByIdArr = Array.prototype.map.call(elementsById, el => el.id);

/**
* identify all element ID's on a page,
* construct array of all element ID's on a page,
*/

const elementsById = document.querySelectorAll('[id]');
const elementsByIdArr = Array.prototype.map.call(elementsById, el => el.id);

for (const el of elementsByIdArr) {
  document.getElementById(el).innerHTML = `My id is &quot;&num;${el}&quot;`;
}
.title {font-weight: bolder; font-size: 24px;}
.description {line-height: 1.8em;}
<div id="primary" class="title"></div>
<div id="description" class="description"></div>

#8


-1  

First of all, I would highly recommend jQuery. It has simplified my JavaScript development soooo much. (See RichieHindle's answer)

首先,我强烈推荐jQuery。它简化了我的JavaScript开发。 (见RichieHindle的回答)

Second, I know that a lot of browsers keep a list of IDs for direct (fast) access, but I don't know of a way to access them. It would probably be browser-specific anyways, so that's probably not the best route.

其次,我知道很多浏览器会保留一个ID列表以供直接(快速)访问,但我不知道如何访问它们。它可能是浏览器特定的,所以这可能不是最好的路线。

Finally, the code:

最后,代码:

var elementList = document.getElementsByTagName("*");
var idList = [];
for (var i in elementList) {
  if (elementList[i].id != "") {
    idList.push(elementList[i].id);
  }
}
// Do something with your array of ids

#1


36  

On modern browsers you can do this via

在现代浏览器上,您可以通过此方式执

document.querySelectorAll('*[id]')

should do the job.

应该做的工作。

If you need all descendants of myElement with IDs, then do

如果你需要myElement的所有后代都带有ID,那么就做

myElement.querySelectorAll('*[id]')

If you want to be really careful to exclude <span id="">, then maybe

如果你想非常小心地排除,那么也许

document.querySelectorAll('*[id]:not([id=""])')

If compatibility with older browsers is required

如果需要与旧版浏览器兼容

var allElements = document.getElementsByTagName("*");
var allIds = [];
for (var i = 0, n = allElements.length; i < n; ++i) {
  var el = allElements[i];
  if (el.id) { allIds.push(el.id); }
}

should leave you with all the IDs in allIds.

应该留下allIds中的所有ID。

If you find you need to just enumerate the IDs under a particular form node, then you can replace document.getElementsByTagName with myFormNode.getElementsByTagName.

如果您发现只需枚举特定表单节点下的ID,则可以将document.getElementsByTagName替换为myFormNode.getElementsByTagName。

If you want to include both IDs and NAMEs, then put

如果您想同时包含ID和NAME,请填写

else if (el.name) { allIds.push(el.name); }

below the if above.

如果在上面。

#2


16  

If you're doing your development using a fairly modern browser, you can use querySelectorAll(), then use Array.prototype.forEach to iterate the collection.

如果您使用相当现代的浏览器进行开发,则可以使用querySelectorAll(),然后使用Array.prototype.forEach来迭代集合。

var ids = document.querySelectorAll('[id]');

Array.prototype.forEach.call( ids, function( el, i ) {
    // "el" is your element
    console.log( el.id ); // log the ID
});

If you want an Array of IDs, then use Array.prototype.map:

如果需要ID数组,请使用Array.prototype.map:

var arr = Array.prototype.map.call( ids, function( el, i ) {
    return el.id;
});

#3


7  

The jQuery selector $('[id]') will get all the elements with an id attribute:

jQuery选择器$('[id]')将获得具有id属性的所有元素:

$('[id]').each(function () {
    do_something(this.id);
});

Working example here: http://jsfiddle.net/RichieHindle/yzMjJ/2/

这里的工作示例:http://jsfiddle.net/RichieHindle/yzMjJ/2/

#4


7  

Get all tags with the wildcard:

使用通配符获取所有标记:

var allElements = document.getElementsByTagName('*');
for(var i = 0; i < allElements.length; i++) {
    // ensure the element has an Id that is not empty and does exist
    // and string other than empty, '', will return true
    allElements[i].id && console.log(allElements[i].id);
}

#5


5  

well, since it is a form, im sure that you want to iterate only over the form elements and not all the tags in the document ( like href , div's etc.. )

好吧,因为它是一个表单,我确定你只想迭代表单元素而不是文档中的所有标签(如href,div等等)。

for (var i=0; i < form.elements.length; i++) {
   var elementId = form.elements[i].id;
}

#6


3  

with jQuery

用jQuery

$('*').map(function() {
   return this.id || null;
}).get().join(',');

this gets all the elements in the DOM, and runs a function on each to return the id (and if undefined, returning null won't return anything. This returns a jQuery object which is then converted to a JavaScript array with get() and this is then converted to a comma-separated string of ids.

这将获取DOM中的所有元素,并在每个元素上运行一个函数来返回id(如果未定义,则返回null将不返回任何内容。这将返回一个jQuery对象,然后使用get()将其转换为JavaScript数组,然后将其转换为逗号分隔的ID字符串。

Try it on this page and you get

在这个页面上试一试就可以了

"notify-container,overlay-header,custom-header,header,portalLink,topbar,hlinks,hlinks-user,hlinks-nav,hlinks-custom,hsearch,search,hlogo,hmenus,nav-questions,nav-tags,nav-users,nav-badges,nav-unanswered,nav-askquestion,content,question-header,mainbar,question,edit-tags,link-post-7115022,close-question-7115022,flag-post-7115022,comments-7115022,add-comment-7115022,comments-link-7115022,answers,answers-header,tabs,answer-7115033,link-post-7115033,flag-post-7115033,comments-7115033,add-comment-7115033,comments-link-7115033,answer-7115042,link-post-7115042,flag-post-7115042,comments-7115042,add-comment-7115042,comments-link-7115042,answer-7115043,link-post-7115043,delete-post-7115043,flag-post-7115043,post-editor-7115043,wmd-button-bar-7115043,wmd-button-row-7115043,wmd-bold-button-7115043,wmd-italic-button-7115043,wmd-spacer1-7115043,wmd-link-button-7115043,wmd-quote-button-7115043,wmd-code-button-7115043,wmd-image-button-7115043,wmd-spacer2-7115043,wmd-olist-button-7115043,wmd-ulist-button-7115043,wmd-heading-button-7115043,wmd-hr-button-7115043,wmd-spacer3-7115043,wmd-undo-button-7115043,wmd-redo-button-7115043,wmd-help-button-7115043,wmd-input-7115043,draft-saved-7115043,communitymode-7115043,wmd-preview-7115043,fkey,author,edit-comment-7115043,edit-comment-error-7115043,submit-button-7115043,comments-7115043,add-comment-7115043,comments-link-7115043,post-form,post-editor,wmd-button-bar,wmd-input,draft-saved,communitymode,wmd-preview,fkey,author,submit-button,show-editor-button,sidebar,qinfo,adzerk2,newsletter-ad,newsletter-ad-header,newsletter-signup-container,newsletter-signup,newsletter-preview-container,newsletter-preview,h-related,feed-link,feed-link-text,prettify-lang,footer,footer-menu,footer-sites,footer-flair,svnrev,copyright"

“通知容器,覆盖头,自定义标题,标题,portalLink,顶栏,hlinks,hlinks用户,hlinks-NAV,hlinks定制,hsearch,搜索,hlogo,hmenus,NAV-问题,导航标签,导航-Users,NAV-徽章,导航,无人接听,NAV-askquestion,内容,提问头,mainbar,问题,编辑标签,链接后7115022,特写问题-7115022,旗后的7115022,评论-7115022 ,添加注释-7115022,评论链接-7115022,答案,答案头,标签,回答-7115033,链接后7115033,旗后的7115033,评论-7115033,添加注释-7115033,评论链接-7115033,回答-7115042,链接后7115042,旗后的7115042,评论-7115042,添加注释-7115042,评论链接-7115042,回答-7115043,链接后7115043,删除,后7115043 ,旗后的7115043,编辑器-7115043后,大规模杀伤性武器按钮栏-7115043,大规模杀伤性武器按钮行7115043,大规模杀伤性武器粗体按钮7115043,大规模杀伤性武器斜体按钮-7115043,大规模杀伤性武器spacer1-7115043 ,WMD链路按钮-7115043,WMD引号按钮-7115043,WMD码按钮-7115043,WMD图像按钮-7115043,WMD-spacer2-7115043,WMD-olist按钮-7115043,WMD-ulist -屁股在-7115043,大规模杀伤性武器的标题按钮-7115043,WMD-HR-按钮7115043,大规模杀伤性武器spacer3-7115043,大规模杀伤性武器撤消键-7115043,大规模杀伤性武器重做按钮-7115043,大规模杀伤性武器的帮助按钮-7115043,大规模杀伤性武器输入7115043,草稿保存-7115043,communitymode-7115043,大规模杀伤性武器预览-7115043,FKEY,作家,编辑,评论-7115043,编辑注释错误-7115043,提交按钮-7115043,评论-7115043,添加注释-7115043,评论链接-7115043,成形后,编辑器后,大规模杀伤性武器按钮栏,大规模杀伤性武器输入,草稿保存,communitymode,大规模杀伤性武器预览,FKEY,作家,提交按钮,显示─编辑键,侧边栏,QINFO,adzerk2,通讯,广告,通讯,广告标题,简报,注册容器,通讯,注册,通讯预览容器,通讯预览,H相关,饲料环节,馈链接文本,美化琅,页脚,页脚,菜单,页脚,网站,页脚,风骚,svnrev,版权”

#7


0  

A simple ES6 (es2015) solution based on answer of user113716

基于user113716的答案的简单ES6(es2015)解决方案

const elementsById = document.querySelectorAll('[id]');
const elementsByIdArr = Array.prototype.map.call(elementsById, el => el.id);

/**
* identify all element ID's on a page,
* construct array of all element ID's on a page,
*/

const elementsById = document.querySelectorAll('[id]');
const elementsByIdArr = Array.prototype.map.call(elementsById, el => el.id);

for (const el of elementsByIdArr) {
  document.getElementById(el).innerHTML = `My id is &quot;&num;${el}&quot;`;
}
.title {font-weight: bolder; font-size: 24px;}
.description {line-height: 1.8em;}
<div id="primary" class="title"></div>
<div id="description" class="description"></div>

#8


-1  

First of all, I would highly recommend jQuery. It has simplified my JavaScript development soooo much. (See RichieHindle's answer)

首先,我强烈推荐jQuery。它简化了我的JavaScript开发。 (见RichieHindle的回答)

Second, I know that a lot of browsers keep a list of IDs for direct (fast) access, but I don't know of a way to access them. It would probably be browser-specific anyways, so that's probably not the best route.

其次,我知道很多浏览器会保留一个ID列表以供直接(快速)访问,但我不知道如何访问它们。它可能是浏览器特定的,所以这可能不是最好的路线。

Finally, the code:

最后,代码:

var elementList = document.getElementsByTagName("*");
var idList = [];
for (var i in elementList) {
  if (elementList[i].id != "") {
    idList.push(elementList[i].id);
  }
}
// Do something with your array of ids