tim.baker
tim.baker

Reputation: 3307

JavaScript .innerHTMLworking only when called manually

I've got a very simple function, of replacing the innerHTML of a element. I've been trying to debug this for hours but simply can't, and it's infuriating.

When called from a button press the JavaScript (as follows) works well, but when called from another function it doesn't work. I am totally lost as to why this might be, and its a fairly core part of my app

  // This loaded function in my actual code is a document listener
  // checking for when Cordova is loaded which then calls the loaded function
  loaded();

  function loaded() {
alert("loaded");
changeText();
  }

  function changeText() {
   alert("started");
   document.getElementById('boldStuff').innerHTML = 'Fred Flinstone';
  }

Button press and HTML to replace

 <div id="main">
  <input type='button' onclick='changeText()' value='Change Text'/>
  <p>Change this text >>  <b id='boldStuff'> THIS TEXT</b> </p> 
 </div>

It is also here in full on JSFiddle

Upvotes: 0

Views: 137

Answers (3)

Sahal
Sahal

Reputation: 4146

You are already changed the innerHTML by calling the function loaded(); on onLoad. Put this in an empty file and same as .html and open with browser and try. I have commented the function loaded();. Now it will be changed in onclick.

<div id="main">
  <input type='button' onclick='changeText();' value='Change Text'/>
  <p>Change this text >>  <b id='boldStuff'> THIS TEXT</b> </p> 
 </div>

<script>

  //loaded();

  function loaded() {
    alert("loaded");
    changeText();
  }

  function changeText() {
   alert("started");
   document.getElementById('boldStuff').innerHTML = 'Fred Flinstone';
  }

</script>

Upvotes: 1

painotpi
painotpi

Reputation: 6996

You script loads before the element (boldStuff) is loaded,

Test Link - 1 - Put the js in a seperate file

Test Link - 2 - put the js at the very end, before closing the <body>

Upvotes: 1

s1lence
s1lence

Reputation: 2188

The problem here is, that the element you're trying to manipulate is not yet existing when you are calling the changeText() function.

To ensure that the code is only executed after the page has finished loading (and all elements are in place) you can use the onload handler on the body element like this:

<body onload="loaded();">

Additionally you should know, that it's very bad practice to manipulate values by using the innerHTML property. The correct way is to use DOM Manipulations, maybe this can help you.

Upvotes: 1

Related Questions