星期一, 11月 22, 2010

DOM, Document Object Model

操作以下這個網頁
web personalization 網頁個人化
你 會不會覺得有點神奇, 它是如何做到的?
關鍵就在 DOM.

With the DOM scripting methods you can:

- Create new elements on the fly.
- Grab all the tags of the document, or grab the text without grabbing the tag text.
- Insert new text, and change or remove text from any element.
- Move whole parts of the document around, or remove parts as fragments and work with them.
- And the best part: all of these new methods should work in any DOM compliant browser. No more browser sniffing. No need to build different versions of the same page for different browsers.

Reference:
Scripting For The 6.0 Browsers, By Scott Andrew LePera

createElement() allows you to create a new tag.

myImg = document.createElement("IMG")

Give definition.

In the above example, our newly born tag has no ID, no SRC and no home in the document yet. So let's give it some definition:

myImg.setAttribute("id","imageOne")
myImg.setAttribute("src","jabberwocky.gif")

Append it within the document "tree".

Now all we need to do is append it to the document body. And to do that, we use the DOM node method appendChild():

docBody = document.getElementsByTagName("body").item(0)
docBody.appendChild(myImg)

沒有留言: