<香港科技大学html+css+js课堂笔记>week3--DOM模型基础

1.DOM含义:

Document Object Model;


2.Eg:

<!DOCTYPE html>
<html>
<head>
    <title>A Simple Web Page</title>
    <meta name="author" content="David Rossiter">
</head>
<body>
    <h1>My Web Page</h1>
    <p>This web page is so awesome!</p>
</body>
</html>



3.whitespace:

A COMPARISON:
1] <body><p>Hello.</p>

<body><p>之间没有空格node

2] <body>
 <p>Hello.</p>

<body><p>之间没有空格节点


4.NODE RELATIONSHIPS:

1>怎样找到节点的位置:

function handleClick(event) {
  event.stopPropagation();
  var node = event.target
  var thisPath = node.nodeName;
  while (node.parentNode) {
    node = node.parentNode;
    thisPath = node.nodeName + " > " + thisPath;
  }
  alert(thisPath);
}

2>为每个节点注册触发器:

// Register the click event handler for all nodes
function attachHandler(node) {
  if(node == null) return;
  node.onclick = handleClick;
        
  for (var i = 0; i < node.childNodes.length; ++i)
    attachHandler(node.childNodes[i]);
} 利用递归!


5.定位节点位置:

1>使用精确的地址:

document.childNodes[0].childNodes[2].childNodes[1].style.color;

2>getElementsByTagName("body"):

document.getElementsByTagName("h2")[0].style.color;

3>getElementById("num_text");

document.getElementById("cute_text").style.color.

4>setAttribute("style", "color:red"):

document.getElementsByTagName("h2")[0].setAttribute("style", "color:yellow");


6.加入节点:

1>createElement("hr") //<hr>表示一条横线。

result = document.createElement("div");

Eg:

newItem = document.createElement("hr");
destParent = document.getElementsByTagName("body")[0];
destParent.insertBefore(newItem, destParent.firstChild);

2>appendChild(....):

result=document.createTextNode("This is dynamically added Text!");      
document.getElementById("my_text").appendChild(result);


7.删除节点:

1>三种方式:(删除某一个节点)

1) var the_node=document.getElementById("firstP");
the_node.parentNode.removeChild(the_node); 
2) var the_node=document.getElementsByTagName("p")[0];
the_node.parentNode.removeChild(the_node); 
3) var the_parent=document.getElementById("theBody");
the_parent.removeChild(the_parent.firstChild);

2>删除网页中的所有节点:

var theNode = document.getElementById("theBody");
while (theNode.firstChild)   // While there is a child
    theNode.removeChild(theNode.firstChild);.

3>复制(节点标签)或(节点标签与内容):

the_node.clone();与 the_node.cloneNode(false)效果相同---复制节点标签。

the_node.clone(true);---复制节点标签与内容。


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值