码迷,mamicode.com
首页 > 其他好文 > 详细

访问文档中的所有元素

时间:2014-09-17 11:51:12      阅读:218      评论:0      收藏:0      [点我收藏+]

标签:des   style   blog   http   color   io   java   ar   for   

<!doctype html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>DOM Example</title>
  <script type="text/JavaScript" src="exampleFindElements.js">
  </script>
</head>
<body>
  <h1>Heading</h1>
  <p>Paragraph</p>
  <h2>Subheading</h2>
  <ul id="eventsList">
    <li>List 1</li>
    <li>List 2</li>
    <li><a href="http://www.baidu.com">Linked List Item</a></li>
    <li>List 4</li>
  </ul>
  <p>Paragraph</p>
  <p>Paragraph</p>
</body>
</html>

 

exampleFindElements.js:

function findElements()
{
var listElements=document.getElementsByTagName(‘li‘);
var paragraphs=document.getElementsByTagName(‘p‘);
var msg=‘This document contains ‘+listElements.length+‘ list items ‘
msg+=‘ and ‘+paragraphs.length+‘ paragraphs.‘;
//alert(msg);
//Get the first paragraph
var firstpara=document.getElementsByTagName(‘p‘)[0];
//Get the second list item
var secondListItem=document.getElementsByTagName(‘li‘)[1];
//Get last list item
var lastListItem=listElements[listElements.length-1];
//Get son Item
var targetLink=document.getElementsByTagName(‘li‘)[2].getElementsByTagName(‘a‘)[0];
//Get by id
var events=document.getElementById(‘eventsList‘);

//Set the value of node
document.getElementsByTagName(‘p‘)[0].firstChild.nodeValue=‘Hello woorld!‘;
alert(firstpara);
alert(secondListItem);
alert(lastListItem);
alert(targetLink);
alert(events);
}


//Get all Chilren node
function myDOMinspector()
{
    var DOMstring=‘‘;
    if(!document.getElementById||!document.createTextNode){return;}
    var demoList=document.getElementById(‘eventsList‘);
    if(!demoList){return;}
    if(demoList.hasChildNodes())
    {
        var ch=demoList.childNodes;
        for(var i=0;i<ch.length;i++)
        {
            DOMstring+=ch[i].firstChild.nodeValue+‘\n‘+ch[i].nodeName+‘\n‘;
        }
        alert(DOMstring);
    }
}

window.onload=findElements;
window.onload=myDOMinspector;

bubuko.com,布布扣bubuko.com,布布扣bubuko.com,布布扣bubuko.com,布布扣bubuko.com,布布扣

bubuko.com,布布扣

 

访问文档中的所有元素

标签:des   style   blog   http   color   io   java   ar   for   

原文地址:http://www.cnblogs.com/vonk/p/3976574.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!