Search code examples
javascripthtmllabelinnerhtml

Change label text using JavaScript


Why doesn't the following work for me?

<script>
    document.getElementById('lbltipAddedComment').innerHTML = 'Your tip has been submitted!';
</script>
<label id="lbltipAddedComment"></label>

Solution

  • Because your script runs BEFORE the label exists on the page (in the DOM). Either put the script after the label, or wait until the document has fully loaded (use an OnLoad function, such as the jQuery ready() or http://www.webreference.com/programming/javascript/onloads/)

    This won't work:

    <script>
      document.getElementById('lbltipAddedComment').innerHTML = 'your tip has been submitted!';
    </script>
    <label id="lbltipAddedComment">test</label>
    

    This will work:

    <label id="lbltipAddedComment">test</label>
    <script>
      document.getElementById('lbltipAddedComment').innerHTML = 'your tip has been submitted!';
    </script>
    

    This example (jsfiddle link) maintains the order (script first, then label) and uses an onLoad:

    <label id="lbltipAddedComment">test</label>
    <script>
    function addLoadEvent(func) {  
          var oldonload = window.onload;  
          if (typeof window.onload != 'function') {  
            window.onload = func;  
          } else {  
            window.onload = function() {  
              if (oldonload) {  
                oldonload();  
              }  
              func();  
            }  
          }  
        }  
    
       addLoadEvent(function() {  
    document.getElementById('lbltipAddedComment').innerHTML = 'your tip has been submitted!';
    
        });  
    </script>