David Cring
David Cring

Reputation: 41

Uncaught TypeError: Cannot read property 'click' of null

I am trying to click a div whose class name is (xyz)

document.querySelector('.header-search-wrap').click();
<iframe src="https://www.gammerson.com" frameborder="0" width="500px" height="900px">
	</iframe>

so I tried to run run below document.querySelector('.xyz').click(); but it gives me

error Uncaught TypeError: Cannot read property 'click' of null

but when I go to elements windows and search of XYZ class and then again go back to console window of chrome and run below code again

document.querySelector('.xyz').click();

surprisingly it works. I don't know what is the problem can any one help me solve the problem. I tried multiple time it only works when I open source code in elements window and then run the code.

Upvotes: 0

Views: 10709

Answers (2)

yuriy636
yuriy636

Reputation: 11661

You can't select a element by querying the document like document.querySelector() if the element is a child in an iframe; if you want to, you have to retrieve its document: Javascript - Get element from within an iFrame

But the other thing is that you can't access an iframe which is not in the same origin (well, I guess, you haven't specified) because the "Same-origin policy" applies: SecurityError: Blocked a frame with origin from accessing a cross-origin frame


And about your statament:

When you open the console it will show you Uncaught TypeError: Cannot read property 'click' of null but when you search for all .header-search-wrap in elements tab and then again execute document.querySelector('.header-search-wrap').click(); it will show you only undefined this means it works

This happens because when you inspect an element in said iframe the DevTools' "context" (Chrome Dev Tools: <page context> and <top frame>?) changes to the iframe's and you can use document.querySelector() freely.

Upvotes: 1

Madhav Chaturvedi
Madhav Chaturvedi

Reputation: 621

Simply whenever you run

document.querySelector('.xyz');

And if it says null that means at that point of time there are no elements with class xyz so calling click() on null results error.

Upvotes: 0

Related Questions