MLZ
MLZ

Reputation: 433

Unable to get JS document.getElementById to work in my rails view

In my views/user/index.html.erb, I have:

<div id="heading">There are <%= @user.length %> users in here</div>

In my assets/javascripts/stuff.js, I have:

document.getElementById("heading").innerHTML = "No one here";

Yet when I reload the page, the js snippet doesn't work, the text is unchanged. However, when I put alert("test") in my `stuff.js file, an alert box pops up, letting me know at least the JavaScript is being picked up.

What am I missing for the getElementById to work?

Upvotes: 0

Views: 1345

Answers (2)

Good Bye Blue sky
Good Bye Blue sky

Reputation: 196

Looks like you're running your script before the DOM load. If that's the case, try putting the call to your code at the end of your body tag.

<body>
<div id="heading">There are <%= @user.length %> users in here</div>

...

<script src="assets/javascripts/stuff.js"></script>
</body>

Upvotes: 1

Hossam Khamis
Hossam Khamis

Reputation: 1202

If you are using rails 5 with Turbolink 5 you should use this event to make sure that the element is there.

document.addEventListener("turbolinks:load", function() {
    document.getElementById("heading").innerHTML = "no one here";
});

If you are using a previous version of Turbolink use page:load instead of turbolinks:load

Upvotes: 3

Related Questions