Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
420 views
in Technique[技术] by (71.8m points)

html - What do people mean by "DOM Manipulation" and how would I do that?

I always hear people talk about DOM this, manipulate the DOM, change the DOM, traverse the DOM; but what exactly does this mean?

What is the DOM and why would I want to do something with it?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The DOM is basically an API you use to interface the document with, and is available in many languages as a library ( JS is one of those languages ). The browser converts all the HTML in your web page to a tree based on the nesting. Pop open Firebug and look at the HTML structure. That is the tree I'm talking about.

If you want to change any HTML you can interact with the DOM API in order to do so.

<html>
 <head><script src="file.js"></script></head>
 <body>blah</body>
</html>

In file.js I can reference the body using:

onload = function() {
    document.getElementsByTagName('body')[0].style.display='none';
}

The getElementsByTagName is a method of the document object. I am manipulating the body element, which is a DOM element. If I wanted to traverse and find say, a span I can do this:

onload = function() {
 var els = document.getElementsByTagName('*');
 for ( var i = els.length; i--; ) {
    if ( els[i].nodeType == 1 && els[i].nodeName.toLowerCase() == 'span' ) {
       alert( els[i] )
    }
 }
}

I am traversing the nodeList given back by getElementsByTagName in the snippet above, and looking for a span based on the nodeName property.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...