元素节点的属性和方法
元素节点的属性
/*
tagName
innerHTML 双标签
value 单标签(input,textarea(虽然是双标签))既一般为表单标签
*/
节点属性只能获取行间样式
<script> /* tagName innerHTML 双标签 value 单标签(input,textarea(虽然是双标签))既一般为表单标签 */ window.onload = function(){ var oDiv = document.getElementById('div1'); //tagName 当前标签的名字 全大写 // alert(oDiv.tagName); /* innerHTML 是标签间内容,并且如果标签含有html代码,会自动解析。 */ // alert(oDiv.innerHTML);//<h1>我是内容</h1> oDiv.innerHTML = "<em>em</em>"; //em } </script> </head> <body> <div id = 'div1'><h1>我是内容</h1></div> </body>
补充:
window.onload = function(){ var oDiv = document.getElementById('div1'); /* 行间属性(只能修改css的内联样式) */ /* alert(oDiv.id);//dox1 alert(oDiv.title);//world alert(oDiv.className); //box */ //修改元素节点属性 /* oDiv.title = "hello";// oDiv 节点的title属性 修给为hello 既将 world修改为hello oDiv.className = 'box22';//oDiv 节点的class属性 修给为box22 既将 box修改为box22 */ // alert(oDiv.style); //object CSS2Properties css样式对象 /* alert(oDiv.style.width);//200px alert(oDiv.style.height);//200px */ /* 凡是带-的css样式属性,需要,将-去掉,后面单词的首字母大写。(例background-color 选择节点属性时要写成 backgroundColor) */ alert(oDiv.style.backgroundColor);//red oDiv.style.backgroundColor = "blue"; //修改元素节点oDiv的style属性的background-color属性 为blue; } </script> </head> <body> <div id = 'div1' class = 'box' title = 'world' style = 'width:200px; height:200px; <h1>我是内容</h1> </div> </body>
【注】获取元素节点的属性一般为: 节点.行间属性名,例如 oDiv.title \ oDiv.style \ oDiv.id, 但是获取class属性时,不能写成 oDiv.class 因为 class 是 js语法中的 一个关健字(保留字),这与css中的属性名冲突了,所以要获取
节点的class属性 要用 className, 既 oDiv.className
元素节点的方法(与元素节点属性对比记忆)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<script>
/*
元素节点的方法。
setAttribute
getAttribute
removeAttribute
行间的属性
*/
window.onload = function(){
var oDiv = document.getElementById('div1');
/* //元素节点属性获取
alert(oDiv.id); //div1
alert(oDiv.title);// hello
//元素节点方法获取
alert(oDiv.getAttribute("id")); //div1
alert(oDiv.getAttribute("title")); //hello
*/
//1、获取class
/*
alert(oDiv.className);//box
alert(oDiv.getAttribute("class"));//box
*/
//2、自定义属性
//我们在div标签中随便写了一个(自定义)属性和属性值 xxx = 'x' ,用于测试 元素节点属性 与元素节点方法获取的区别
//测试一
alert(oDiv.xxx);// undefined
alert(oDiv.getAttribute("xxx")); //x
/*这里我们就很明显的看出了两者区别 .getAttribute 是支持自定义的属性的,而元素节点的属性则不能*/
//测试二
oDiv.className = 'box2'; //利用元素节点属性将div的class属性值改为 box2
oDiv.setAttribute('class', 'box3'); //利用元素节点方法将div的class属性值改为 box3
/*可见在修改属性值方面这两中方法并没有明显的区别*/
//测试三
oDiv.xxx = "yyy";//结果改不掉xxx依然等于x(不会报错) //利用元素节点属性将div的自定义xxx属性值改为 yyy
oDiv.setAttribute("xxx", "yyy"); //xxx = 'yyy' 可以修改成功
/*可见只有setAttribute对自定义属性有效*/
//测试四
oDiv.title = ""; //title 利用元素节点属性只能将属性值赋成空,但不能删除
oDiv.removeAttribute("title"); //可以将属性值删除
}
</script>
</head>
<body>
<div id = 'div1' title = 'hello' name = 'world' class = 'box' xxx = 'x'>div</div>
</body>
</html>
上面代码测试效果图:
测试一 无
测试二:
元素节点属性修改class属性值

元素节点方法修改class属性值:

测试三:
元素节点和属性修改不了
元素节点方法修改自定义属性值

测试四:
元素节点属性使属性值为空

removeAttribute移除属性值


浙公网安备 33010602011771号