Introducing innerHTML
Note:
This discussion includes use of variables and operators,
which are explained in the following lessons of the week 02 lecture.
Please re-read this lesson after reading the entire week 02 lecture.
Question:
What is innerHTML?
Answer:
innerHTML is the html source code between an opening and closing tag.
For example, Hello JavaScript would be the innerHTML of the p tag in the below example:
<p>Hello JavaScript</p>
Question:
Do all tags have an innerHTML?
Answer:
No. Some tags do not, such as input and img tags.
Question:
How do I access innerHTML with JavaScript?
Answer:
The easiest way is for the tag to have an id.
For example:
<p id="p1">Hello JavaScript</p>
Then your JavaScript can access that particular tag using getElementById:
var myPtag = document.getElementById("p1");
Question:
Once I access a particular tag, how do I access its innerHTML?
Answer:
Use .innerHTML. For example:
var myPtext = myPtag.innerHTML;
or
var myPtext = document.getElementById("p1").innerHTML;
Question:
The above examples read from the innerHTML, how do I write to the innerHTML?
Answer:
Assign the value of a variable (or a literal) to the innerHTML
For example:
var myText = "Hello CS-555";
document.getElementById("p1").innerHTML = myText;
or
var myTag, myText = "Hello CS-555";
myTag = document.getElementById("p1");
myTag.innerHTML = myText;
Question:
Where can I learn more about innerHTML?
Answer:
For a live demonstration, visit:
innerHTML
For completing class exercises, please download and unzip the web developer toolbox from:
web developer toolbox