document.querySelector not working on dynamic content

4.2k Views Asked by At

Why when I'm using document.querySelector on a dynamic HTML element, it won't give me the current dynamically set data? Is there a way to get the current data?

Example:

If I go to this stripe page with dynamic html, and I copy the JS path of this element:

enter image description here When I press paste and run the code in the console I get:

document.querySelector("#Full > table > tbody > tr > td:nth-child(1)")

returns-> <td>EUR</td>

But I would expect to get:

returns-> <td>USD</td>

I noticed that no matter what country I pick for Viewing support settlement currencies for which sets the dynamic HTML, the document query selector always returns the result as if that tab was on the first country in the list, Austria.

2

There are 2 best solutions below

2
On BEST ANSWER

querySelector returns the first item it finds that match. If you look at the source code the "dynamic" code is it just shows and hides a section. Each section has a table.

So what do they use to show it selected, but it is done on multiple levels. To get to the element that you are seeing as #Full, it would be

document.querySelector(".tabs-tab.selected .tabs-tab.selected")

The full selector would be

document.querySelector('.tabs-tab.selected .tabs-tab.selected > table > tbody > tr > td:nth-child(1)')
0
On

If you really want to get data from that that path than you can use following code. just find the full xpath of website element using developer tools from chrome or firefox. Than replace fullXpath with your Fullxpath.

Note: I notice That normal xpath also does not work, so thats why use full xpath instead of xpath.

 let fullXpath =  "/html/body/div[2]/div/div[2]/div[2]/div/div/div/div[2]/div/div[1]/article/section[2]/div/div/div[34]/div/div/div[1]/table/tbody/tr[1]/td[1]";
    document.evaluate(fullXpath, document, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue.innerHTML;

This will give you the desire result you are looking.