<!DOCTYPE html> <html lang="en" xmlns="http://www.w3.org/1999/xhtml"> <head> <meta charset="utf-8" /> <title>getElementById and innerHTML</title> <script> window.onload = function () { var main = document.getElementById('main'); main.innerHTML += "<p>This element was added dynamically.</p>"; console.log(main); } </script> </head> <body> <h1>DOM Elements</h1> <div id="main"> <p>Manipulating the DOM is fun!</p> <p>Javascript can be used to manipulate the DOM</p> </div> </body> </html>
<!DOCTYPE html> <html lang="en" xmlns="http://www.w3.org/1999/xhtml"> <head> <meta charset="utf-8" /> <title>Changing DOM Elements</title> <style> .blue { color: blue; font-weight: bold; } .red { color: red; font-weight: bold; text-decoration: overline; } </style> <script> window.onload = function () { var content = document.getElementById('main'); //content.setAttribute('class', 'blue'); //content.setAttribute('class', 'red'); content.style.backgroundColor = "yellow"; content.style.fontWeight = "bold"; content.style.borderBottom = "5px solid black" } </script> </head> <body> <h1>DOM Elements</h1> <div id="main"> <p>Manipulating the DOM is fun!</p> <p>Javascript can be used to manipulate the DOM</p> </div> </body> </html>
<!DOCTYPE html> <html lang="en" xmlns="http://www.w3.org/1999/xhtml"> <head> <meta charset="utf-8" /> <title>Adding and Deleting Elements</title> <script> window.onload = function () { var theList = document.getElementById('myList'); var node = document.createElement("LI"); var text = document.createTextNode("Yes"); node.appendChild(text); theList.appendChild(node); var node2 = document.createElement("LI"); var text2 = document.createTextNode("Tower of Power"); node2.appendChild(text2); theList.appendChild(node2); /* it's unclear why this works as it does */ // removes first LI tag theList.removeChild(theList.childNodes[1]); // removes nothing visible, more unseen nodes theList.removeChild(theList.childNodes[2]); // removes second LI tag theList.removeChild(theList.childNodes[2]); } </script> </head> <body> <ul id="myList"> <li>Journey</li> <li>REO Speedwagon</li> </ul> </body> </html>
<!DOCTYPE html> <html lang="en" xmlns="http://www.w3.org/1999/xhtml"> <head> <meta charset="utf-8" /> <title>Locating Elements</title> <script> window.onload = function () { var result = document.getElementById('result'); // returns HTMLCollection var elements = document.getElementsByTagName('p'); result.innerHTML = elements; console.log(elements); console.log(elements[0]); var x = document.getElementsByClassName('last'); console.log(x); console.log(x[0]); } </script> </head> <body> <h1>DOM Elements</h1> <div id="main"> <p>Manipulating the DOM is fun!</p> <p>Javascript can be used to manipulate the DOM</p> <p class="last">This is the third node!</p> <div id="result"></div> </div> </body> </html>