javascript找對象與使用對象方法
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>找對象</title>
</head>
<body>
<h4>標題</h4>
<div id="test1">
<p>1</p>
<p>2</p>
<p>3</p>
</div>
<div class="test2" >
test
</div>
username:<input type="text" name="username" value="Mark">
username:<input type="text" name="username2" value="Mark">
<script>
//『用ID查詢』
//返回對象 ( objectHTMLElement )
console.log(document.getElementById("test1"));
//操作方式
document.getElementById("test1").style.border= "1px solid red";
//『用標簽查詢』
//返回值對象集合( ObjectHTMLCollection) ,可當成數組取用,即使只找到1個對象,也包裝成ObjectHTMLCollection
console.log(document.getElementsByTagName("p"));
var p = document.getElementsByTagName("p");
//操作方式
p[1].style.background="blue";
//『在表單中用name查詢』
//返回值是對象節點清單 (ObjectNodeList),可當成數組取用,即使只找到1個對象,也包裝成ObjectNodeList
var x1 = document.getElementsByName('username');
//操作方式
x1[0].value='Lucy';
// document.getElementsByName('username')[1].innerHTML='Lucy';
//『用CLASS查詢』
//返回值對象集合 ( objectHTMLCollection ),可當成數組取用,即使只找到1個對象,也包裝成ObjectHTMLCollection
//alert(document.getElementsByClassName("test2").length);
//var div = document.getElementsByClassName('test2');
var x2= document.getElementsByClassName("test2");
x2[0].style.background="gray";
</script>
</body>
</html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>找對象</title>
</head>
<body>
<h4>標題</h4>
<div id="test1">
<p>1</p>
<p>2</p>
<p>3</p>
</div>
<div class="test2" >
test
</div>
username:<input type="text" name="username" value="Mark">
username:<input type="text" name="username2" value="Mark">
<script>
//『用ID查詢』
//返回對象 ( objectHTMLElement )
console.log(document.getElementById("test1"));
//操作方式
document.getElementById("test1").style.border= "1px solid red";
//『用標簽查詢』
//返回值對象集合( ObjectHTMLCollection) ,可當成數組取用,即使只找到1個對象,也包裝成ObjectHTMLCollection
console.log(document.getElementsByTagName("p"));
var p = document.getElementsByTagName("p");
//操作方式
p[1].style.background="blue";
//『在表單中用name查詢』
//返回值是對象節點清單 (ObjectNodeList),可當成數組取用,即使只找到1個對象,也包裝成ObjectNodeList
var x1 = document.getElementsByName('username');
//操作方式
x1[0].value='Lucy';
// document.getElementsByName('username')[1].innerHTML='Lucy';
//『用CLASS查詢』
//返回值對象集合 ( objectHTMLCollection ),可當成數組取用,即使只找到1個對象,也包裝成ObjectHTMLCollection
//alert(document.getElementsByClassName("test2").length);
//var div = document.getElementsByClassName('test2');
var x2= document.getElementsByClassName("test2");
x2[0].style.background="gray";
</script>
</body>
</html>
留言