Most JS Code Manipulates Elements On An HTML Page We Can Examine Elements' State
Most JS Code Manipulates Elements On An HTML Page We Can Examine Elements' State
1
(DOM)-unit 4
most JS code
manipulates elements
on an HTML page
we can examine
elements' state
e.g. see whether a box
is checked
we can change state
e.g. insert some new
text into a div
we can change styles
DOM element objects
2
Accessing elements:
3
document.getElementById
var name = document.getElementById("id");
JS
<button onclick="changeText();">Click me!</button>
<span id="output">replace me</span>
<input id="textbox" type="text" />
HTML
function changeText() {
var span = document.getElementById("output");
var textBox = document.getElementById("textbox");
textbox.style.color = "red";
}
JS
CS380
Accessing elements:
4
document.getElementById
document.getElementById returns the
DOM object for an element with a given
id
can change the text inside most
elements by setting the innerHTML
property
can change the text in form controls by
setting the value property
CS380
Changing element style:
5
element.style
Property or style
Attribute
object
color color
padding padding
background-color backgroundColor
border-top-width borderTopWidth
Font size fontSize
Font famiy fontFamily
CS380
Preetify
6
function changeText() {
//grab or initialize text here
CS380
7 More Javascript Syntax
CS380
Variables
8
// single-line comment
/* multi-line comment */
JS
CS380
Math object
11
CS380
Special values: null and
12
undefined
var ned = null;
var benson = 9;
// at this point in the code,
// ned is null
// benson's 9
// caroline is undefined
JS
CS380