HTML要素を得るための3つの方法

2437 ワード

一.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>
 
二.getElements ByName方法
<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>
 
 
三.getElements ByTagName方法
<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>