訪問文檔中的所有元素

來源:互聯網
上載者:User

標籤: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;

 

訪問文檔中的所有元素

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.