Friday, January 6, 2012

Javascript code sample: Get all elements with ID

Call function document.getElementsByTagName('*') using widecard '*' to retrieve all element with ID.

Example:
Javascript code sample: Get all elements with ID


<!doctype html>
<head>
<title>Mobile-Web-App: Test Javascript</title>
<meta charset="utf-8">

<script>
function myOnLoad(){

var allElements = new Array();
var result = "=== all elements with ID : ===" + "<" + "br/" + ">";;
allElements = document.getElementsByTagName('*');


for (var i=0; i < allElements.length; i++)
{
if (allElements[i].id)
{
result = result + allElements[i].id + " " + "<" + "br/" + ">";;
}
}

var arrMyName = new Array();
elementResult = document.getElementById("result");
elementResult.innerHTML = result;


}

window.onload = myOnLoad;

</script>


</head>
<body>
<h1>Mobile-Web-App: Javascript Exercise</h1>
<p id="title"><b>Get All elements with ID</b></p>

<p id="msg" name="myname">Hello JavaScript!</p>
<p id="myBlog" name="myname">Mobile-Web-App</p>
<div id="myURL" name="myname">
<p id="innerP">Inner p</p>
<a href="http://mobile-web-app.blogspot.com/">http://mobile-web-app.blogspot.com/</a>
</div>

<p>No ID</p>

<p id="result"></p>

</body>
</html>


No comments:

Post a Comment