Let us assume, I have a <label> element on my web page, with just an ID.
The label shows nothing on the browser, since "lblName" has no value. We can assign a value to the label dynamically using a simple one-line code.
<label id="lblName"></label>
Note: Please do not leave the article "mid way", because I have explained the difference between properties innerHTML and innerText at the end of this tutorial.
1) Using JavaScript innerHTML Property
In the first method, I am assigning a value to the label using the innerHTML property.
<script>
document.getElementById('lblName').innerHTML = 'Hi, I am Arun Banik';
</script>
Browser Support:
Chrome 39.0 - Yes | FireFox 34.0 - Yes | Internet Explorer 10 - Yes | Safari - Yes
Try it Yourself
2) Using JavaScript innerText property
Here in the second method, I am assigning a value to the <label> using JavaScript innerText property.
<script> document.getElementById('lblName').innerText = 'Hi, I am Arun Banik'; </script>
Browser Support:
Chrome 39.0 - Yes | FireFox 34.0 - Yes | Internet Explorer 10 - Yes | Safari - Yes
Both the methods work fine on different browsers (see Browser Support).
Now, you must be wondering, what possible difference does both the properities have. Yes, there is a difference.
Difference between innerHTML and innerText
The name of each property defines itself.
👉 The innerHTML property allows us to write HTML codes along a text value. I can set the text as bold, italic, "underline it" and even set a "colour" to the text.
For example, in the above text "Hi, I am Arun Banik", suppose I would like to set the string Arun Banik as bold. This is how I will do it.
<script> document.getElementById('lblName').innerHTML = 'Hi, I am <b> Arun Banik </b>'; </script>
Remember: Properties are case sensitive.
The output now would be,
Hi, I am Arun Banik
Look carefully at the end of the code, I have added the string Arun Banik between the <b> ... </b> tag.
Similarly, you can "underline" the text using the <u> and </u> tag.
document.getElementById('lblName').innerHTML = 'Hi, I am <u> Arun Banik </u>';
👉 However, the innerText property allows us to add plain text values only. It "won't" format the assigned text. Therefore, even you if you add an HTML element to the text using "innerText", it would assign the value as it is (along with the element).
We have seen two different procedures to assign values to a <label> control using JavaScript properties innerHTML and innerText respectively. In addition, I have explained the difference between the two properties.
Similarly, using the above-mentioned properties, you can retrieve or get the values from the <label> control.