人们对“DOM操作”意味着什么?我该怎么办? [英] What do people mean by "DOM Manipulation" and how would I do that?

查看:81
本文介绍了人们对“DOM操作”意味着什么?我该怎么办?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我总是听到人们谈论这个DOM,操纵DOM,改变DOM,遍历DOM;但是这是什么意思?



什么是DOM,为什么要使用它做某事?

解决方案

DOM 基本上是一个用于将文档与该文档进行接口的API,并且作为库可以在许多语言中使用(JS是这些语言之一)。浏览器将您网页中的所有HTML转换为基于嵌套的树。 Pop打开Firebug并查看HTML结构。



如果要更改任何HTML,您可以与DOM API进行交互,以便这样做。

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

file.js 我可以参考身体使用:

  onload = function(){
document.getElementsByTagName('body')[0] 。显示=无;
}

getElementsByTagName 文档对象的方法。我正在操纵 body 元素,它是一个DOM元素。如果我想穿越并找到说话,我可以这样做:

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

我正在上面的代码段中遍历getElementsByTagName返回的nodeList,并根据 nodeName 属性查找跨度。 p>

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?

解决方案

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.

这篇关于人们对“DOM操作”意味着什么?我该怎么办?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆