js中擷取頁面元素節點的幾種方式

來源:互聯網
上載者:User

標籤:

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title></title>
<!--
使ie以IE8的模式運行
-->
<meta http-equiv="X-UA-Compatible" content="IE=EmulateIE8" >
<script type="text/javascript">

/**
* 得到頁面元素節點的幾種方式
*/

//通過id選取器去得到
function getDom01() {
//擷取一個
var div = document.getElementById("box1");
console.log(div);
}

//通過標籤名得到元素
function getDom02(){
//會得到所有的 與名字相同的標籤
var divs = document.getElementsByTagName("div");
console.log(divs[0]);
}
//根據名字得到
function getDom03(){
//只能得到 原生就有name屬性的元素 不能是自訂的
var div = document.getElementsByName("box2");
document.getElementsByClassName("box1");
console.log(div[0]);
}
//IE7 以及以前的版本 不支援
function getDom04(){
var div = document.querySelector("#box1");
console.log(div);
}
//IE7 以及以前的版本 不支援
function getDom05(){
var span = document.querySelectorAll(".box > span");
console.log(span.length);
}
</script>
<style type="text/css">
.box{
border: 1px solid red;
width: 450px;
height: 100px;
}

.box span{
border-left: 1px solid green;
border-right: 1px solid green;
margin: 0 10px;
padding: 0 5px;
}
</style>
</head>
<body>
<input type="button" onclick="getDom01()" value="getDom01"/>
<input type="button" onclick="getDom02()" value="getDom02"/>
<input type="button" onclick="getDom03()" value="getDom03" name="box2"/>
<input type="button" onclick="getDom04()" value="getDom04" name="box2"/>
<input type="button" onclick="getDom05()" value="getDom05" name="box2"/>
<hr/>
<div class="box" id="box1" name="box2">
<span>this is a span in div</span>
<span>this is a span in div</span>
<span>this is a span in div</span>
<span>this is a span in div</span>
</div>
</body>
</html>

js中擷取頁面元素節點的幾種方式

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.