您的位置:首页 > 其它

DOM(文档对象模型)学习笔记(二)

2017-11-12 22:59 369 查看

Document类型

document对象是window对象的一个属性,可以将其作为全局对象使用。document节点具有以下特性:

nodeType的值为9;

nodeName的值为“#document”;

nodevalue的值为null;

ownerDocument的值为null;

访问文档的子节点:

快捷方式:

documentElement属性指向< html >元素;

document.body 取得对body的引用;

document.title=”new title”取得对标题的引用;

alert(document.URL); 取得完整的url;

alert(document.domain)只包含域名;

alert(document.referrer);

alert(document.documentElement.firstChild.nodeName);// 获取html标签 再获取html第一个标签head
alert(document.childNodes.length); //document有两个孩子结点
alert(document.childNodes.item(0).nodeName);  //第一个子节点html
alert(document.childNodes.item(1).childNodes.item(0).nodeName); //第二个子节点htmi的第一个子节点head


查找元素方法:

1.getElementById(),Document类型方法,接收一个参数,:取得的元素的ID。严格匹配大小写。

2.getElementByTagName(),Document类型方法,接收一个参数:元素的标签名,注意方法名中多个”s”,该方法返回的是一个类似NodeList对像,使用时需要用方括号或者item()获取。

3.getElementsByName(),只有HTMLDocument类型才有,返回带有给定name特性的所有元素。下面代码演示了javascript通过getElementByName获取单选框的值。

<head>
<script type="text/javascript">
function gender(){
var gender=document.getElementsByName("gender");
for(var i=0;i<gender.length;i++)
if(gender[i].checked)
alert(gender[i].value);

}
</script>
</head>

<body>
<input type="radio" value="男" name="gender" checked="checked"/>男
<input type="radio" value="女" name="gender"  />女
<input type="button" onclick="gender()" value="提交"/>
</body>


特殊集合:

document.anchors,包含文档中所有带name特性的< a >元素;

document.forms,包含文档中所有的< form >元素;

document.images,包含文档中所有的< img >元素;

document.links,包含文档中所有带href特性的< a >元素;

文档写入

通过write()和writeln()可以动态写入字符串,包括html文档。

<head>
<script type="text/javascript">
document.write("<div id='box'>write方法</div>");
document.write("write方法2");*/

</script>
<style type="text/css">

box{ width:100px; height:100px; border:1px solid red;}

</style>
</head>


还可以通过write()和writeln()引入外部文件,js,css等。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息