Access all elements in the document

Source: Internet
Author: User

<! 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 <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 ('lil ');
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 ('lil') [1];
// Get last list item
VaR lastlistitem = listelements [listelements. Length-1];
// Get son item
VaR targetlink = Document. getelementsbytagname ('lil') [2]. getelementsbytagname ('A') [0];
// Get by ID
VaR events = Document. getelementbyid ('eventlist ');

// 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 ('eventlist ');
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;

 

Access all elements in the document

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.