18.04.2016 Views

Professional JavaScript For Web Developers

javascript for learners.

javascript for learners.

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

DOM Basics<br />

To access the element with the ID “div1”, you can use the getElementsByTagName() like this:<br />

var oDivs = document.getElementsByTagName(“div”);<br />

var oDiv1 = null;<br />

for (var i=0; i < oDivs.length; i++){<br />

if (oDivs[i].getAttribute(“id”) == “div1”) {<br />

oDiv1 = oDivs[i];<br />

break;<br />

}<br />

}<br />

Or, you could use getElementById() like this:<br />

var oDiv1 = document.getElementById(“div1”);<br />

As you can see, this is a much more streamlined way to get a reference to a specific element.<br />

Internet Explorer 6.0 also returns an element if the given ID matches the name<br />

attribute of an element. This is a bug, and one that you should be very careful of.<br />

Creating and manipulating nodes<br />

So far, you’ve learned how to access various nodes inside of a document, but that’s just the beginning of<br />

what can be done using the DOM. You can also add, remove, replace, and otherwise manipulate nodes<br />

within a DOM document. This functionality is what makes the DOM truly dynamic.<br />

Creating new nodes<br />

The DOM Document has a number of methods designed to create various types of nodes, even though<br />

the browser document object doesn’t necessarily support each of these methods in all browsers. The following<br />

table lists the methods included in DOM Level 1 and which browsers support each one.<br />

Method Description IE MOZ OP SAF<br />

createAttribute Creates an attribute node with X X X –<br />

(name)<br />

the given name<br />

createCDATASection Creates a CDATA Section with a – X – –<br />

(text)<br />

text child node containing tex<br />

createComment Creates a comment node X X X X<br />

(text)<br />

containing text<br />

createDocument Creates a document fragment X X X X<br />

Fragment()<br />

node<br />

createElement Creates an element with a tag X X X X<br />

(tagname)<br />

name of tagname<br />

Table continued on following page<br />

173

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!