4.8.2.JSDOM对象控制HTML元素详解

时间:2023-05-04 21:45:26

1

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>DOM对象控制HTML</title>
</head>
<body>
<p name="pn">hello</p>
<p name="pn">hello</p>
<p name="pn">hello</p>
<a id="aid" title="得到了a标签的属性">hello</a>
<a id="aid2">aid2</a>
<ul><li>1</li><li>2</li><li>3</li></ul>
<div id="div">
<p id="pid">div的P元素</p>
</div>
<script>
function getName() {
var count = document.getElementsByName("pn");
alert(count.length);
var p = count[2];
p.innerHTML = "World";
}
function getAttr() {
var anode = document.getElementById("aid");
var attr = anode.getAttribute("id");
alert(attr);
}
function setAttr() {
var anode = document.getElementById("aid2");
anode.setAttribute("title", "动态设置a的title属性");
var attr = anode.getAttribute("title");
alert(attr);
}
function getChildNode() {
var childnode = document.getElementsByTagName("ul")[0].childNodes;
alert(childnode.length);
alert(childnode[0].nodeType)
}
function getParentNode() {
var div = document.getElementById("pid");
alert(div.parentNode.nodeName);
}
function createNode() {
var body = document.body;
var input = document.createElement("input");
input.type = "button";
input.value = "按钮";
body.appendChild(input);
}
function addNode() {
var div = document.getElementById("div");
var node = document.getElementById("pid");
var newnode = document.createElement("p");
newnode.innerHTML = "动态添加体格p元素";
div.insertBefore(newnode, node);
}
function removeNode() {
var div = document.getElementById("div");
var p = div.removeChild(div.childNodes[1]);
}
function getSize() {
var width = document.body.offsetWidth || document.documentElement.offsetWidth;
var height = document.body.offsetHeight;
alert(width + " " + height);
}
getSize();
</script>
</body>
</html>