JavaScript Document 基础教程文档
收录于 2023-04-20 00:10:05 · بالعربية · English · Español · हिंदीName · 日本語 · Русский язык · 中文繁體
document对象
Document对象代表整个html文档。
在浏览器中加载html文档时,它成为Document对象。代表html文档的是
root元素。它具有属性和方法。借助于Document对象,我们可以将动态内容添加到网页中。
如前所述,它是窗口的对象。所以
window.document
与
document
根据W3C-
" W3C Document对象模型(DOM)是平台和语言无关的接口,允许程序和脚本动态访问和更新文档的内容,结构和样式。
Document对象的属性
让我们看看Document对象可以访问和修改的属性。
Document对象的方法
我们可以通过其方法访问和更改文档的内容。
Document对象的重要方法是如下:
方法 | 说明 |
write("string") | 将给定的字符串写在文档上。 |
writeln("string") | 将给定的字符串写在文档的末尾,换行符。 |
getElementById() | 返回具有给定id值的元素。 |
getElementsByName() | 返回所有具有给定名称值的元素。 |
getElementsByTagName() | 返回所有具有给定标签名称的元素。 |
getElementsByClassName() | 返回具有给定类名称的所有元素。 |
按document对象访问字段值
在此示例中,我们将按用户获取输入文本的值。在这里,我们使用
document.form1.name.value 来获取名称字段的值。
在这里,
document 是表示以下内容的根元素
form1 是表单的名称。
name 是输入文本的属性名称。
value 是属性,它返回输入文本的值。
我们来看一个简单的Document对象示例,该示例显示带有欢迎消息的名称。
<script type="text/javascript">
function printvalue(){
var name=document.form1.name.value;
alert("Welcome: "+name);
}
</script>
<form name="form1">
Enter Name:<input type="text" name="name"/>
<input type="button" onclick="printvalue()" value="print name"/>
</form>
function printvalue(){
var name=document.form1.name.value;
alert("Welcome: "+name);
}
</script>
<form name="form1">
Enter Name:<input type="text" name="name"/>
<input type="button" onclick="printvalue()" value="print name"/>
</form>