Search code examples
javascriptconsole

Trouble getting an item through the JavaScript Console


I am trying to get an element of a page using the Console. Here is the code:

var ELEMENT = document.querySelector('div.flexCenter-3_1bcw.flex-1O1GKY.justifyCenter-3D2jYp.alignCenter-1dQNNs')

And I want to get a specific 'thing' from the element:

ELEMENT.__reactProps$81cjqqgfk4j

Unfortunately, the .__reactProps$ 'thing' changes every time I visit the page. Sometimes, it might be __reactProps$25jwbxmtle or __reactProps$94maqnwnty, and so on. What can I do here?

When I type ELEMENT.attributes, this comes up:

NamedNodeMap {0: class, class: class, length: 1}
    0: class
        ownerDocument: document
            .__reactEvents$81cjqqgfk4j

The .__reactEvents item always ends with the same string as the .__reactProps item.

Is there a way to get the name of this item from the attributes? (Because that would be enough for me.)


Solution

  • You can use Object.keys(ELEMENT) to get all the keys for that element and than search for the needed one. This will extract prefix, the random ID:

    var ELEMENT = document.querySelector('div.flexCenter-3_1bcw.flex-1O1GKY.justifyCenter-3D2jYp.alignCenter-1dQNNs');
    
    let id = null;
    for(let i = 0, keys = Object.keys(ELEMENT); i < keys.length; i++)
    {
      if ((id = keys[i].match(/^__react[^$]*(\$.+)$/)))
      {
        id = id[1];
        break;
      }
    }
    
    console.log(id);