How do I enumerate all of the html id's in a document with javascript?

前端 未结 8 725
伪装坚强ぢ
伪装坚强ぢ 2021-01-31 07:54

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.

To under

8条回答
  •  面向向阳花
    2021-01-31 08:39

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

    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 "#${el}"`;
    }
    .title {font-weight: bolder; font-size: 24px;}
    .description {line-height: 1.8em;}

提交回复
热议问题