Unique element ID, even if element doesn't have one

前端 未结 13 1168
抹茶落季
抹茶落季 2020-12-14 00:43

I\'m writing a GreaseMonkey script where I\'m iterating through a bunch of elements. For each element, I need a string ID that I can use to reference that element later. The

相关标签:
13条回答
  • 2020-12-14 01:28

    If you can write to the DOM (I'm sure you can). I would solve this like this:

    Have a function return or generate an ID:

    //(function () {
    
      var idCounter = new Date().getTime();
      function getId( node ) {
        return (node.id) ? node.id : (node.id = 'tempIdPrefix_' + idCounter++ );
      }
    
    //})();
    

    Use this to get ID's as needed:

    var n = document.getElementById('someid');
    getId(n);  // returns "someid"
    
    var n = document.getElementsByTagName('div')[1];
    getId(n);  // returns "tempIdPrefix_1224697942198"
    

    This way you don't need to worry about what the HTML looks like when the server hands it to you.

    0 讨论(0)
提交回复
热议问题