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

前端 未结 8 787
伪装坚强ぢ
伪装坚强ぢ 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:32

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

    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:

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

提交回复
热议问题