113

Why doesn't the following work for me?

<script>
    document.getElementById('lbltipAddedComment').innerHTML = 'Your tip has been submitted!';
</script>
<label id="lbltipAddedComment"></label>
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
phil crowe
  • 1,445
  • 2
  • 11
  • 15
  • 4
    Because when you script try to change label innerHtml, lbltipAddedComment actually not present at page. Insert script after label or use jquery $(document).ready() – Andrew Orsich Dec 20 '10 at 10:26

8 Answers8

166

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>
Konerak
  • 39,272
  • 12
  • 98
  • 118
  • I think .textContent answer is actually the correct one – Paul Taylor Mar 22 '18 at 14:30
  • 2
    Well @PaulTaylor, this answer is here since 2010 and has 92 upvotes (and now, your downvote). The question used innerHTML so I only changed what was necessary to get his code moving. While I feel it's always OK to suggest extra ideas ("hey, btw, use textcontent instead of innerhtml/innertext), that was not OP's problem... There is no need to downvote. – Konerak Mar 22 '18 at 14:38
  • Okay but did he ever get it working his last comment was that nothing worked so it was my understanding that your solution didnt work, certianly didnt work for me, looks this https://jsfiddle.net/cfxrLpe9/4/ works with textContent but not innerHtml, why is that ? – Paul Taylor Mar 22 '18 at 14:42
  • @PaulTaylor The answer probably worked for the OP as he marked this answer as accepted. You have a typo in your code. You are using innerHtml instead of innerHTML as the answer shows. https://jsfiddle.net/cfxrLpe9/6/ – Randall Flagg Mar 23 '18 at 01:13
26

Have you tried .innerText or .value instead of .innerHTML?

Nathan Campos
  • 28,769
  • 59
  • 194
  • 300
GordonM
  • 31,179
  • 15
  • 87
  • 129
18

Because a label element is not loaded when a script is executed. Swap the label and script elements, and it will work:

<label id="lbltipAddedComment"></label>
<script>
    document.getElementById('lbltipAddedComment').innerHTML = 'Your tip has been submitted!';
</script>
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
mvladic
  • 1,179
  • 2
  • 12
  • 15
  • 1
    Oh, didn't notice that! Yes, if the posted code is reflective of the real code (isn't using jquery to fire on document.ready or similar) then that's a reason why it wouldn't work as well. – GordonM Dec 20 '10 at 10:30
13

Use .textContent instead.

I was struggling with changing the value of a label as well, until I tried this.

If this doesn't solve try inspecting the object to see what properties you can set by logging it to the console with console.dir as shown on this question: How can I log an HTML element as a JavaScript object?

Community
  • 1
  • 1
Pochi
  • 13,391
  • 3
  • 64
  • 104
  • Thank you. I suspect (but haven't rigorously confirmed) that my use-case is similar to that in the question: I was trying to retrieve and/or change the text of a label that has a nested input element, e.g. I wanted to retrieve and/or change the `"enter info here:"` part of the following: ``. Only `.textContent` worked, and none of `.innerHTML`, `.innerText` or `.value` worked. (Disclaimer: I've only checked in Chrome.) – Andrew Willems Oct 31 '17 at 02:06
  • Thankyou I hit the same problem – Paul Taylor Mar 22 '18 at 14:29
  • 4
    @AndrewWillems unfortunately `.textContent` and `.innerText` (while fine for reading), didn't work for my firefox60 for writing (it also erased embedded input field, just like `.innerHTML`). So I've had to resort to `document.getElementById('myLabel').childNodes[0].nodeValue="new label text"` (of course, index might be something other then 0, which makes is a little kludgy but worked it for me) – Matija Nalis Nov 23 '18 at 23:38
12

Here is another way to change the text of a label using jQuery:

<script>
  $("#lbltipAddedComment").text("your tip has been submitted!");
</script>

Check the JsFiddle example

mustapha mekhatria
  • 3,495
  • 1
  • 20
  • 26
10

Using .innerText should work.

document.getElementById('lbltipAddedComment').innerText = 'your tip has been submitted!';
timss
  • 9,982
  • 4
  • 34
  • 56
Shilpa
  • 101
  • 1
  • 2
1

Try this:

<label id="lbltipAddedComment"></label>
<script type="text/javascript"> 
      document.getElementById('<%= lbltipAddedComment.ClientID %>').innerHTML = 'your tip has been submitted!';
</script>
0

Apparently there are several ways to change the text of a label, I found this link page below, which has an explanation of each of these ways (it is a lot of text, so I attached only the examples here).

In my case none of them were working, even using the javascript code after uploading the tag, because I'm using ESP32 as a server, and Arduino IDE to upload the page, for some reason the IDE (1.8.19) was not reading the files from the new location I put the files, I had to delete the old folder, to close the IDE, and only then was it possible to update the files, I discovered this when looking at the source code of the page in the browser.

How to Change Label Text Using JavaScript?

The following approaches can be utilized to change label text in JavaScript:

    “innerHTML” property.
    “innerText” property.
    jQuery “text()” and “html()” methods.

“innerHTML” property:

<center><body>
<label id = "lbl">DOM</label>
<br><br>
<button onclick= "labelText()">Click Here</button>
</body></center>

function labelText(){
 let get = document.getElementById('lbl')
 get.innerHTML= "The abbreviated name is Document Object Model";
}

“innerText” property:

<center><body>
 Enter a Name: <input type= "text" id= "name" value= "" autocomplete= "off">
<p><input type= "button" id= "bt" value= "Change Label Text" onclick= "labelText()"></p>
<label id="lbl">N/A</label>
</body></center>

function labelText() {
 let get = document.getElementById('lbl');
 let name = document.getElementById('name').value;
 get.innerText = name;
}

jQuery “text()” and “html()” methods:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<center><body>
<label id = "lbl1">This is the following Website:</label>
<br><br>
<label id = "lbl2">Content:</label>
<br><br>
<button onclick= "labelText()">Click for Website</button>
<button onclick= "labelText2()">Click for Content</button>
</body></center>

function labelText() {
 $('#lbl1').text("Linuxhint")
}
function labelText2() {
 $('#lbl2').html("JavaScript")
}

https://linuxhint.com/change-label-text-javascript/

R R
  • 11
  • 2
  • This does not really answer the question. If you have a different question, you can ask it by clicking [Ask Question](https://stackoverflow.com/questions/ask). To get notified when this question gets new answers, you can [follow this question](https://meta.stackexchange.com/q/345661). Once you have enough [reputation](https://stackoverflow.com/help/whats-reputation), you can also [add a bounty](https://stackoverflow.com/help/privileges/set-bounties) to draw more attention to this question. - [From Review](/review/late-answers/34382135) – Moritz Ringler May 15 '23 at 09:59