Except where otherwise noted, the contents of this document are Copyright 2012 Marty Stepp, Jessica Miller, and Victoria Kirst. All rights reserved. Any redistribution, reproduction, transmission, or storage of part or all of the contents in any form is prohibited without the author's expressed written permission.
<button onclick="okayClick();">OK</button>
// called when OK button is clicked
function okayClick() {
alert("booyah");
}
// where element is a DOM element object
element.event = function;
<button id="ok">OK</button>
document.getElementById("ok").onclick = okayClick;
<head> <script src="myfile.js" type="text/javascript"></script> </head> <body> ... </body>
// global code
var x = 3;
function f(n) { return n + 1; }
function g(n) { return n - 1; }
x = f(x);
script
tag
body
<head> <script src="myfile.js" type="text/javascript"></script> </head> <body> <div><button id="ok">OK</button></div>
// global code document.getElementById("ok").onclick = okayClick; // error: document.getElementById("ok") is null
head
is processed before page's body
has loaded
window.onload
event
// this will run once the page has finished loading function functionName() { element.event = functionName; element.event = functionName; ... } window.onload = functionName; // global code
window.onload
event that occurs at that momentwindow.onload
handler we attach all the other handlers to run when events occur
<!-- look Ma, no JavaScript! -->
<button id="ok">OK</button>
// called when page loads; sets up event handlers function pageLoad() { document.getElementById("ok").onclick = okayClick; } function okayClick() { alert("booyah"); } window.onload = pageLoad; // global code
()
when attaching the handler
window.onload = pageLoad();window.onload = pageLoad;okButton.onclick = okayClick();okButton.onclick = okayClick;
window.onLoad = pageLoad;window.onload = pageLoad;
function(parameters) { statements; }
window.onload = function() { var okButton = document.getElementById("ok"); okButton.onclick = okayClick; }; function okayClick() { alert("booyah"); }
window.onload = function() { var okButton = document.getElementById("ok"); okButton.onclick = function() { alert("booyah"); }; };
How would we do each of the following in JavaScript code? Each involves modifying each one of a group of elements ...
div
s of class puzzle
to random x/y locations.ul
list with id
of TAs
to have a gray background.<p> This is a paragraph of text with a <a href="/path/page.html">link in it</a>. </p>
<div id="main" class="foo bar"> <p>Hello, <em>very</em> happy to see you!</p> <img id="icon" src="images/borat.jpg" alt="Borat" /> </div>
Property | Description | Example |
---|---|---|
tagName
|
element's HTML tag |
document.getElementById("main").tagName is "DIV"
|
className
|
CSS classes of element |
document.getElementById("main").className is "foo bar"
|
innerHTML
|
content inside element |
document.getElementById("main").innerHTML is "\n <p>Hello, <em>ve...
|
src
|
URL target of an image |
document.getElementById("icon").src is "images/borat.jpg"
|
<input id="sid" type="text" size="7" maxlength="7" /> <input id="frosh" type="checkbox" checked="checked" /> Freshman?
Property | Description | Example |
---|---|---|
value
|
the text in an input control |
document.getElementById("sid").value could be "1234567"
|
checked
|
whether a box is checked |
document.getElementById("frosh").checked is true
|
disabled
|
whether a control is disabled (boolean) |
document.getElementById("frosh").disabled is false
|
readOnly
|
whether a text box is read-only |
document.getElementById("sid").readOnly is false
|
var paragraph = document.getElementById("welcome");
paragraph.innerHTML = "Welcome to our site!"; // change text on page
DOM element objects have the following properties:
innerHTML
: text and/or HTML tags inside a nodetextContent
: text (no HTML tags) inside a node
innerHTML
, but not supported in IE6
value
: the value inside a form controlinnerHTML
// bad style!
var paragraph = document.getElementById("welcome");
paragraph.innerHTML = "<p>text and <a href="page.html">link</a>";
innerHTML
can inject arbitrary HTML content into the pageinnerHTML
to inject HTML tags; inject plain text only
<button id="clickme">Color Me</button>
window.onload = function() { document.getElementById("clickme").onclick = changeColor; }; function changeColor() { var clickMe = document.getElementById("clickme"); clickMe.style.color = "red"; }
Property | Description |
---|---|
style
|
lets you set any CSS style property for an element |
camelCasedNames
backgroundColor
, borderLeftWidth
, fontFamily
.style
when setting styles
var clickMe = document.getElementById("clickme");clickMe.color = "red";clickMe.style.color = "red";
likeThis
, not like-this
clickMe.style.font-size = "14pt";clickMe.style.fontSize = "14pt";
clickMe.style.width = 200;clickMe.style.width = "200px"; clickMe.style.padding = "0.5em";
function okayClick() {this.style.color = "red";this.className = "highlighted"; }
.highlighted { color: red; }
every node's DOM object has the following properties:
name(s) | description |
---|---|
firstChild , lastChild
|
start/end of this node's list of children |
childNodes
|
array of all this node's children |
nextSibling , previousSibling
|
neighboring nodes with the same parent |
parentNode
|
the element that contains this node |
<p id="foo">This is a paragraph of text with a <a href="/path/to/another/page.html">link</a>.</p>
<div> <p> This is a paragraph of text with a <a href="page.html">link</a>. </p> </div>
div
above have?"\n\t"
(before/after the paragraph)a
tag?
document
and other DOM objects (* = HTML5):
name | description |
---|---|
getElementsByTagName
|
returns array of descendents with the given tag, such as "div"
|
getElementsByName
|
returns array of descendents with the given name attribute (mostly useful for accessing form controls)
|
querySelector *
|
returns the first element that would be matched by the given CSS selector string |
querySelectorAll *
|
returns an array of all elements that would be matched by the given CSS selector string |
highlight all paragraphs in the document:
var allParas = document.querySelectorAll("p"); for (var i = 0; i < allParas.length; i++) { allParas[i].style.backgroundColor = "yellow"; }
<body> <p>This is the first paragraph</p> <p>This is the second paragraph</p> <p>You get the idea...</p> </body>
highlight all paragraphs inside of the section with ID "address"
:
// var addrParas = document.getElementById("address").getElementsByTagName("p");
var addrParas = document.querySelectorAll("#address p");
for (var i = 0; i < addrParas.length; i++) {
addrParas[i].style.backgroundColor = "yellow";
}
<p>This won't be returned!</p>
<div id="address">
<p>1234 Street</p>
<p>Atlanta, GA</p>
</div>
name | description |
---|---|
document.createElement("tag")
|
creates and returns a new empty DOM node representing an element of that type |
document.createTextNode("text")
|
creates and returns a text node containing given text |
// create a new <h2> node
var newHeading = document.createElement("h2");
newHeading.innerHTML = "This is a heading";
newHeading.style.color = "green";
Every DOM element object has these methods:
name | description |
---|---|
appendChild(node)
|
places given node at end of this node's child list |
insertBefore(new, old)
|
places the given new node in this node's child list just before old child
|
removeChild(node)
|
removes given node from this node's child list |
replaceChild(new, old)
|
replaces given child with new node |
var p = document.createElement("p"); p.innerHTML = "A paragraph!"; document.getElementById("main").appendChild(p);
function slideClick() { var bullets = document.getElementsByTagName("li"); for (var i = 0; i < bullets.length; i++) { if (bullets[i].innerHTML.indexOf("children") >= 0) { bullets[i].parentNode.removeChild(bullets[i]); } } }
removeChild
method to remove its children from the page
innerHTML
hackingWhy not just code the previous example this way?
function slideClick() { document.getElementById("thisslide").innerHTML += "<p>A paragraph!</p>"; }
"
and '
function slideClick() { this.innerHTML += "<p style='color: red; " + "margin-left: 50px;' " + "onclick='myOnClick();'>" + "A paragraph!</p>"; }