100 likes | 262 Views
Document Object Model (DOM). JavaScript manipulation of the DOM. DOM Tree. < p >Some text <a href =“http:// www.go.com ”>Go</a>. </ p >. DOM Tree. <div id=“content”><h1>Title</h1> < p class=“box”>box text</ p >Not in paragraph </div>. DOM Tree.
E N D
Document Object Model (DOM) JavaScript manipulation of the DOM
DOM Tree <p>Some text <a href=“http://www.go.com”>Go</a>. </p>
DOM Tree <div id=“content”><h1>Title</h1> <p class=“box”>box text</p>Not in paragraph </div>
DOM Tree <body><h1>Title</h1><p>This is<i>italic <b>bold</b> text </i>.</p> </body>
DOM Tree <ul id=“mylist”> <li class=“link><a href=“test.html”>Link</a></li> <li>Not a link</li> </ul>
JavaScript – document object • JavaScript code is always executed in a web browser in the context to a rendered document. • In English, JavaScript is inside a web page (XHTML document). The document object refers to the XHTML document itself. • varx = document.FunctionName(); • x is usually a “node” object. • or a text object.
How to manipulate content <div id=“content”> <h1>Title</h1> <p>Paragraph</p> <h2>Heading</h2> <h2>Another one</h2> </div> vard = document.getElementById(‘content’); varh2s = d.getElementByTagName(‘h2’); varsecondH2 = h2s[1]; varx = secondH2.innerHTML; // x would store “Another one” secondH2. innerHTML= “New one”; // The line above actually changes the live displayed web page.
How to manipulate attributes <a id=“homelink” href=“http://www.siena.edu”>Home</a> varh = document.getElementByID(‘homelink’).getAttribute(‘href’); alert(h); varx = document.getElementByID(‘homelink’); x.setAttribute(‘href’, ‘http://www.espn.com’); x.setAttribute(‘alt’, ‘Siena College’);
Creating Document structure • x = document.createElement(‘body’) • makes a new element/tag • <body></body> • x.createTextNode(‘hi’) • add text inside a tag • <body>hi</body>
Append • x.appendChild(document.createElement(‘h2’)) • <body>hi<h2></h2></body> • x.insertBefore(document.createElement(‘h1’)) • <body><h1></h1>hi<h2></h2></body> • Also, • removeChild– must identify the node by using getElementByID or TagName • cloneChild– must identify the node, can copy the entire tree below the node.