0

I'm trying to perform the very simple task of selecting all of the sections in my DOM using jQuery, but for some reason $sections is null everytime I do the following:

HTML:

<div class="container">
    <div id="bl-main">
        <section>
        ...
        </section>
        <section>
        ...
        </section>
    </div>
</div>
<script>
    $(function() {
        Boxlayout.init();
    });
</script>

Javascript:

var Boxlayout = (function() {
    var $el = $( "#bl-main" );
    var $sections = $el.children("section");
    ...
    // init function and more code down below
});

Does anybody see what I'm doing wrong?

Edit: I'm working on this project in Rails, so it's very likely that I've messed up some part of Rails. The HTML is located in app/assets/views/static_pages.html.erb, and the JS is located in app/assets/javascripts/static_pages.js

Cody Ma
  • 317
  • 2
  • 11
  • Where is the JS code located compared to the HTML you are trying to query? – Felix Kling May 24 '14 at 16:32
  • 2
    Your code works fine: http://jsfiddle.net/8D26t/. I would suggest you have an error elsewhere in your page. – Rory McCrossan May 24 '14 at 16:33
  • Totally forgot to mention, but this is a Rails project which I'm fairly new to. The HTML is located in app/assets/views/static_pages.html.erb, and the JS is located in app/assets/javascripts/statick_pages.js. – Cody Ma May 24 '14 at 16:37
  • 2
    I'd argue that the JS code is located before the HTML and thus you are trying to access elements that don't exist yet. See [Why does jQuery or a DOM method such as `getElementById` not find the element?](http://stackoverflow.com/q/14028959/218196) and http://learn.jquery.com/about-jquery/how-jquery-works/ . – Felix Kling May 24 '14 at 16:39
  • Your argument would be correct! It seems like I don't understand the inner-workings of rails well-enough. I copy pasted the code from the separate JS file to the bottom of my HTML file, and everything works as intended. Thanks you! – Cody Ma May 24 '14 at 16:44
  • The HTML should be located in app/views/controller_name/static_pages.html.erb and not in app/assets/views/static_pages.html.erb. assets is to keep only stylesheets,js files and images. – Shamsul Haque May 24 '14 at 16:44
  • Moved it there but still no luck. Currently only working if I copy all of the JS into a ` – Cody Ma May 24 '14 at 16:50
  • Did you actually read the answer in the question I linked to? Put your code inside `$(function() { .... })`. Also see the jQuery tutorial I linked to. It explains all of that. – Felix Kling May 24 '14 at 17:50
  • Yep, all of my code is inside the document.ready call. I've updated my original post with more code to hopefully make things a bit clearer – Cody Ma May 24 '14 at 22:00

0 Answers0