Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript + Chrome, console can't find element until after I inspect it

I am trying to edit an element's input value. I am 100% sure it is loaded in the DOM. However, when I mess with it in console, it cannot find the element until I inspect it. Going by the token name property there is something going on. But because inspect seems to 'convert' it to be able to be found, surely there is a way to do it automatically?

Code in question: https://jsfiddle.net/h8oyLdv4/1/

If I put $('input') in the console it returns null. If I inspect any of the forms, it returns with

<input class="FORMshrt2" name="fd_co_firstname" type="text" maxlength="100" value="">

Also, document.querySelector('input') returns

<input type="hidden" name="csrfmiddlewaretoken" value="XXbWi2ygjOsJ8igaEa9MvFb5Nm7xznOD">

but once I inspect the element, it returns

<input class="FORMshrt2" name="fd_co_firstname" type="text" maxlength="100" value="">
like image 480
JustaCookie Avatar asked May 17 '17 07:05

JustaCookie


1 Answers

From the csrfmiddlewaretoken thing, you're apparently doing this on jsFiddle.

The issue is that the console starts out attached to the main window, in which $ is a function that's a shortcut for getElementById (overriding Chrome console's built-in $, which is a shortcut for querySelectorAll). Since there's no element with the id input, $('input') returns null. Since the first input on jsFiddle's main window is the csrfmiddlewaretoken input, querySelector finds that input.

But if you right-click and inspect an element in the Result frame, the console is then attached to the frame instead, which has your input elements and your scripts and such in it, so (depending on what's in your scripts) $ is either Chrome console's default $ or jQuery or whatever else you have loaded, and because your content is there, you find it when you use $ or querySelector.

like image 98
T.J. Crowder Avatar answered Sep 30 '22 06:09

T.J. Crowder