1

I would like to experimenting with onfocus event on page: http://www.w3schools.com/jsref/tryit.asp?filename=tryjsref_onfocus

I use Chrome developer console (Ctrl+Shift+I). When I try to access the input element by typing in the console:

document.getElementsByTagName("input")

I get two hidden input elements instead of the text input element. Screenshot image: https://i.stack.imgur.com/hOX97.png So What's going on here, and how can access those elements on the "tryout" pages?

Konstantin
  • 2,983
  • 3
  • 33
  • 55
  • 1
    I believe they use iFrames on W3Schools for their tryout pages, which means that the elements are not available without accessing the iFrame first. You'll have to approach it from that angle. – David Mar 25 '16 at 21:58

1 Answers1

0

@David is right, each iframe is a separate javascript context.

If you want to execute javascript in context of an iframe, see this question

Alternatively, you can use element picker of Chrome Dev Tools (ctrl-shift-c) and then in console type $0, it will return the last focused element. When you then focus something else, you can use $0 to the newly focused element, $1 for previously focused one etc.

See Dev Tools command line API

Community
  • 1
  • 1
jakub.g
  • 38,512
  • 12
  • 92
  • 130
  • Blocked a frame with origin "http://www.w3schools.com" from accessing a cross-origin frame. – Konstantin Mar 25 '16 at 23:53
  • Thx, now it works, I just have to select the right iframe context from the appropriate dev tools menu. My problem now is that when I call "focus()" on the text input element, the onfocus event handler isn't triggered. What can be the problem? – Konstantin Mar 25 '16 at 23:59
  • I think the `.focus()` method just gives the focus to the element but doesn't execute the listeners. You can execute `.onfocus()` to directly call the registered listener on an element, or you may try to [dispatch an event](https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/dispatchEvent) – jakub.g Mar 28 '16 at 19:20