Clip Art innerHTML
Pierce Home
Computer Science 555 Website Development using JavaScript and AJAX - 3 Units
Section:
3179
Instructor:
Brad Gilbert
Pierce Mailbox:
612
Email:
pierce@wavethunder.com
Wednesday Office Hours:
5:00 -   5:40 PM COSC 1507
Wednesday Lab:
5:45 -   7:50 PM COSC 1507
Wednesday Lecture:
7:55 - 10:00 PM MATH 1511
Other classes:
CS-575
innerhtml

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

Brad Gilbert · Fall 2011
Computer Science · Pierce College · Woodland Hills CA · 818-719-6401