JavaScript HTML DOM
DOM: Document Object Model
Finding Elements by ID
[Link]("demo").innerHTML = __________
Finding Elements by Tag
<p>Hello World!</p>
<p>This example demonstrates the <b>getElementsByTagName</b> method.</p>
<p id="demo"></p>
<script>
var x = [Link]("p");
[Link]("demo").innerHTML =
'The text in first paragraph (index 0) is: ' + x[0].innerHTML;
</script>
Finding Elements by Class
<p>Hello World!</p>
<p class="intro">The DOM is very useful.</p>
<p class="intro">This example demonstrates the <b>getElementsByClassName</b> method.</p>
<p id="demo"></p>
<script>
var x = [Link]("intro");
[Link]("demo").innerHTML =
'The first paragraph (index 0) with class="intro": ' + x[0].innerHTML;
</script>
Finding Elements by CSS Selector
<p>Hello World!</p>
<p class="intro">The DOM is very useful.</p>
<p class="intro">This example demonstrates the <b>getElementsByClassName</b> method.</p>
<p id="demo"></p>
<script>
var x = [Link]("intro");
[Link]("demo").innerHTML =
'The first paragraph (index 0) with class="intro": ' + x[0].innerHTML;
</script>
Finding Elements by Object Collections
• [Link]
• [Link]
• [Link]
• [Link]
• [Link]
• [Link], etc.
Finding Elements by [Link]
<form id="frm1" action="/action_page.php"> <script>
First name: <input type="text" name="fname" function myFunction() {
value="Donald"><br>
var x = [Link]["frm1"];
Last name: <input type="text" name="lname"
value="Duck"><br><br> var text = "";
<input type="submit" value="Submit"> var i;
</form> for (i = 0; i < [Link] ;i++) {
text += [Link][i].value + "<br>";
<p>Click "Try it" to display the value of each }
element in the form.</p> [Link]("demo").innerHTML
= text;
<button onclick="myFunction()">Try it</button> }
</script>
<p id="demo"></p>
The “onload” Event
<body onload="checkCookies()">
<p id="demo"></p>
<script>
function checkCookies() {
var text = "";
if ([Link] == true) {
text = "Cookies are enabled.";
} else {
text = "Cookies are not enabled.";
}
[Link]("demo").innerHTML = text;
}
</script>
The “onchange” Event
<script> Enter your name: <input
function myFunction() { type="text" id="fname"
onchange="myFunction()">
var x =
[Link]("fname
"); <p>When you leave the input
[Link] = [Link](); field, a function is triggered which
transforms the input text to upper
} case.</p>
</script>
The “onmouseover” and “onmouseout”
Events
<div onmouseover="mOver(this)" <script>
onmouseout="mOut(this)" function mOver(obj) {
style="background- [Link] = "Thank You"
color:#D94A38;width:120px;heig }
ht:20px;padding:40px;">
Mouse Over Me</div> function mOut(obj) {
[Link] = "Mouse Over Me"
}
</script>
The “onmousedown” and “onmousup”
Events
<div <script>
onmousedown="mDown(this)" function mDown(obj) {
onmouseup="mUp(this)" [Link] = "#1ec5e5";
style="background- [Link] = "Release Me";
color:#D94A38;width:90px;height }
:20px;padding:40px;">
function mUp(obj) {
Click Me</div>
[Link]="#D94A38";
[Link]="Thank You";
}
</script>