0

I am trying to modify the text of a div element. It isn't even changing the existing text, it is just adding a paragraph element to the top of the screen.

Code:

function addContent() {
  document.getElementById("test").innerHTML = "Something";
}
<div id="test">This is some text</div>
<button class="btn btn-primary btn-lg" id="getStartedButton" onclick="addContent()">Get Started</button>

But instead of editing the text within the test div. It creates a new p element at the top of the page with the id="test"

Does this have anything to do with bootstraps?

Thanks in advance!

UPDATE: Amy below helped with this issue, thank you!

  • 3
    working fine here - https://jsfiddle.net/avebhcc4/ – Paul Fitzgerald Jan 18 '17 at 22:46
  • What browser are you using, OP? –  Jan 18 '17 at 22:47
  • 3
    [I can't reproduce the problem](http://jsbin.com/vocugu/1/edit?html,js,output) — when you create a [mcve] don't forget to verify it! (You should probably try to make use of the live demo feature available in the toolbar of the Stackoverflow Editor too) – Quentin Jan 18 '17 at 22:47
  • @Amy I'm using Chrome and inspecting with that as well. – Burninrock24 Jan 18 '17 at 22:47
  • My fiddle also works fine https://jsfiddle.net/grxn0s2f/. – amflare Jan 18 '17 at 22:48
  • 1
    OP, is your JavaScript code *after* the related HTML? If it is before the HTML on your page, it might not find the element since the DOM hasn't rendered it yet. –  Jan 18 '17 at 22:48
  • @Amy That seemed to be the problem *facepalm* thank you! – Burninrock24 Jan 18 '17 at 22:51
  • No problem. We've all faced this exact issue at some point in time. It's a super easy mistake to make because it isn't obvious its a mistake, *at all*. –  Jan 18 '17 at 22:54

1 Answers1

3

Ensure your JavaScript code is after the related HTML elements. This is because the code can run before the DOM has finished rendering the document. If that's the case, your code won't actually find the element.

You can have JS code at the top of your document without issue as long as you execute that code after the DOM has rendered. So, a JS method at the top, and at the bottom of the document, you call that function. This is fine. Calling these functions inside the document's onload event is advisable.

In general its a good idea for your JS to be placed at the end of the body tag. This isn't always possible, but its a good habit to have.