dom manipulation

Tryit Editor



1. DOM manipulation via javascript: getElementById & innerHTML

- getElementById() searches for the element with the UNIQUE id specified
- The innerHTML property refers to ALL the HTML code within a specific element such as <p> or <div>

COPY THE html CODE BELOW & PASTE HERE

<html> <head> <script type="text/javascript"> var g=0; function gebi() { var s = ""; var x = 1; while(x <= 3) { s += "<h3>ID " + x + " times and g " + g + "</h3>"; x++; g++; } document.getElementById('target').innerHTML += s; } function showInner() { var el = document.getElementById('target').innerHTML; alert(el); } </script> </head> <body> <h3 onclick="gebi()">click here to change innerHTML</h3> <h3 onclick="showInner()">click here to report innerHTML</h3> <p id="target"> </p> </body> </html>



2. DOM manipulation via javascript:   CLICK HERE to get the elements by TAG NAME by calling All().       (<p onclick="All()">)


<html> <head> <script type="text/javascript"> function All() { var j; j= document.getElementsByTagName('html')[0].innerHTML; alert("HTML: " + j); j= document.getElementsByTagName('body')[0].innerHTML; alert("BODY: " +j); j= document.getElementsByTagName('div')[0].innerHTML; alert("DIV 0: " + j); j= document.getElementsByTagName('div')[1].innerHTML; alert("DIV 1: " + j); j= document.getElementById('dom').innerHTML; alert("ById (dom): " + j); } </script> </head> <body> <div onclick="All()">click here to get html by tag</div> <br /> <div>just a normal div</div> </body> </html>



3. Array! and Three Loops (click here to execute the code below and append at bottom of page)


// explain... var array = []; var index = 0; var output = ""; var limit = parseInt(window.prompt("enter size of array: ", 10)); // what happens ? do { array[index] = index*3; index++; } while (index < limit); // what happens ?? for(var i=0; i<array.length; i++) { output += array[i] + " "; } output += "<hr />"; document.getElementById("target").innerHTML += output; // what is WRONG with output (subtle)?? index=0; output=""; while(index < array.length) { if(array[index++]%2 == 0) output += array[index] + " "; } output += "<hr />"; document.getElementById("target").innerHTML += output;