-6

I am working on Ruby on Rails and a simple jQuery won´t execute over an element like this:

$("header").hide();

However, if i wrap it into a function and call it with document.ready it does the right thing:

function myCode() {
    $("header").hide();
}

$(document).ready(myCode);

Why it does not work straight forward?? I have installed gem jquery-rails and even have //=required jquery.min.js in the application.js file.

Thanks for the help!

  • 1
    Why should it work until the document is loaded? – nicael Jun 04 '16 at 20:31
  • 1
    *"Why?"* Element has to exist when you run that code. Pretty basic fundamental of javscript and dom manipulation. Same as you can't eat a pizza that hasn't been delivered yet – charlietfl Jun 04 '16 at 20:32
  • 2
    [Why does jQuery or a DOM method such as getElementById not find the element?](https://stackoverflow.com/questions/14028959/why-does-jquery-or-a-dom-method-such-as-getelementbyid-not-find-the-element) – Jonathan Lonowski Jun 04 '16 at 20:34

1 Answers1

-2

If the document is not ready, the DOM isn't built yet. The header element doesn't exist when that code runs, so nothing happens. To perform DOM manipulation, you must wait until the page is fully loaded, that is, on $(document).ready.

Eran Goldin
  • 937
  • 12
  • 21
  • Not entirely accurate. Whole dom doesn't necessarily need to be loaded. Can place that code immediately after the element without `$(document).ready` and will work fine – charlietfl Jun 04 '16 at 20:36
  • That's true, thanks for the correction! – Eran Goldin Jun 04 '16 at 20:37
  • i am confused.. so you say this should work straight ahead as the first line of code for application.js? $("header").hide(); – Ignacio Palma Balboa Jun 04 '16 at 21:09
  • Yes and no. Strictly it works, but there's no guarantee that the DOM object exists at the time of its execution. You can either do it when the document is `ready`, or perform the script *after* the code that creates the header element. – Eran Goldin Jun 05 '16 at 21:33