Java Reference
In-Depth Information
When you click the OK button, you'll see the text become left‐aligned (Figure 9-7).
figure 9-7
This HTML page contains one
<p/>
element with an
id
value of
paragraph1
. You use this value in
the JavaScript code to find the element node and store its reference in the
pElement
variable with the
getElementById()
method:
var pElement = document.getElementById("paragraph1");
Now that you have a reference to the element, you use the
setAttribute()
method to set the
align
attribute to
center
:
pElement.setAttribute("align", "center");
The result of this code moves the text to the center of the browser's window.
You then use the
getAttribute()
method to get the
align
attribute's value and display it in an
alert
box:
alert(pElement.getAttribute("align"));
This code displays the value
"center"
in the
alert
box.
Finally, you remove the
align
attribute with the
removeAttribute()
method, effectively making the
text left‐aligned.