Several ways to get page element nodes in JS

Source: Internet
Author: User

<! DOCTYPE html>
<meta charset= "UTF-8" >
<title></title>
<!--
Make IE run in IE8 mode
-
<meta http-equiv= "x-ua-compatible" content= "IE=EMULATEIE8" >
<script type= "Text/javascript" >

/**
* Several ways to get page element nodes
*/

Through the ID selector to get
function GetDom01 () {
Get a
var div = document.getElementById ("Box1");
Console.log (DIV);
}

Get elements by tag name
function getDom02 () {
Will get all the same tags as the name
var divs = document.getelementsbytagname ("div");
Console.log (Divs[0]);
}
Get it by name
function GetDom03 () {
You can only get the original. An element with the name attribute cannot be customized
var div = document.getelementsbyname ("Box2");
Document.getelementsbyclassname ("Box1");
Console.log (Div[0]);
}
IE7 and previous versions do not support
function getDom04 () {
var div = document.queryselector ("#box1");
Console.log (DIV);
}
IE7 and previous versions do not support
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>
<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"/>
<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>

Several ways to get page element nodes in JS

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.