一.getElementById方法
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>无标题文档</title>
<script type="text/javascript" >
function showText()
{
var oText = document.getElementById("my_text");//得到文本框元素
oText.value = "haha";//向文本框中赋值
}
</script>
</head>
<body>
<input type="text" id="my_text" />
<input type="button" onclick="showText()" value="向文本框中赋值" />
</body>
二.getElementsByName方法
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>无标题文档</title>
<script type="text/javascript" >
function showText()
{
var oText = document.getElementsByName("txt");//得到所有name为txt的元素集合
for(var i = 0; i < oText.length; i++)
{
oText[i].value = i;
}
}
</script>
</head>
<body>
<input type="text" name="txt" />
<input type="text" name="txt" />
<input type="text" name="txt" />
<input type="text" name="txt" />
<input type="text" name="txt" />
<input type="text" name="txt" />
<input type="button" onclick="showText()" value="向文本框中赋值" />
</body>
三.getElementsByTagName方法
<title>无标题文档</title>
<script type="text/javascript" >
function showText()
{
var oText = document.getElementsByTagName("input");//得到所有input对象
for(var i = 0; i < oText.length; i++)
{
alert(oText[i].type);//显示该节点的类型
}
}
</script>
</head>
<body>
<input type="text" name="txt" />
<input type="checkbox" name="cb" />
<input type="password" name="pwd" />
<input type="button" onclick="showText()" value="显示" />
</body>
本文介绍了三种常用的DOM操作方法:getElementById用于获取指定ID的元素;getElementsByName返回具有相同名称的所有元素集合;getElementsByTagName则返回文档中所有指定标签名的元素集合。

被折叠的 条评论
为什么被折叠?



