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

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

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

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

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

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

    below the if above.

    0 讨论(0)
  • 2021-01-31 08:49

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

    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.

    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
    
    0 讨论(0)
提交回复
热议问题