核心DOM中的公共的属性和方法
核心DOM中的公共的属性和方法
注:核心DOM中查找节点(标记),都是从根节点开始的(html节点)。
节点访问
nodeName:节点名称。
nodeValue:节点的值。只有文本节点才有值,元素节点没有值。nodeValue的值只能是“纯文本”,不能含有任何的HTML标记或CSS属性。
firstChild:第1个子节点。
lastChild:最后1个子节点。
childNodes:子节点列表,是一个数组。
parentNode:父节点。
查找标记的方法
document.firstChild
document.firstChild.lastChild
document.body
对节点的属性操作
setAttribute(name,value):给某个节点添加一个属性。
getAttribute(name):获取某个节点属性的值。
removeAttribute(name):删除某个节点的属性。
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>php.cn</title>
<script type="text/javascript">
window.onload = function(){
//查找body节点
var node_body = document.all.div1;
//查找img节点
var imgObj = node_body.firstChild;
//增加属性
imgObj.setAttribute("src","https://img.php.cn/upload/course/000/000/009/580ae23c4a88a881.jpg");
imgObj.setAttribute("width","400");
imgObj.setAttribute("border","2");
imgObj.setAttribute("style","cursor:pointer;");
//删除border属性
imgObj.removeAttribute("border");
}
</script>
</head>
<body ><div id="div1"><img /></div></body>
</html>节点的创建
document.createElement(tagName):创建一个指定的HTML标记,一个节点
tagName:是指不带尖括号的HTML标记名称。
举例:var imgObj = document.createElement(“img”)
parentNode.appendChild(childNode):将创建的节点,追加到某个父节点下。
parentNode代表父节点,父节点必须存在。
childNode代表子节点。
举例:document.body.appendChild(imgObj)
parentNode.removeChild(childNode):删除某个父节点下的子节点。
parentNode代表父节点。
childNode代表要删除的子节点。
举例:document.body.removeChild(imgObj)
<!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8" />
<title>php.cn</title>
<script >
//网页加载完成后
window.onload = function(){
//创建一个<img>标记
var imgObj = document.createElement("img");
//增加属性
imgObj.setAttribute("src","/upload/course/000/000/009/580ae23c4a88a881.jpg");
imgObj.setAttribute("width","400");
//将创建的图片节点,挂载到某个父节点下
document.body.appendChild(imgObj);
}
</script>
</head>
<body>
</body>
</html>

一辆想出轨的无轨电车
觉得刚入门,现在又出来了
8年前 添加回复 0