Friday, January 6, 2012

Get array of HTML elements with specified name - getElementsByName

The function document.getElementsByName(n) return a array of elements with name of n.

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

<script>
function myOnLoad(){

var arrMyName = new Array();
arrMyName = document.getElementsByName("myname");

for(var i = 0; i < arrMyName.length; i++)
{
var obj = arrMyName.item(i);

obj.style.color = "#00ff00";
obj.innerHTML = "It's the item: " + i + " : " + obj.innerHTML;

}

alert("There are " + arrMyName.length + " elements with name of 'myname'.");

}

window.onload = myOnLoad;

</script>


</head>
<body>
<h1>Mobile-Web-App: Test Javascript</h1>
<p>How to access HTML elements from JavaScript, using document.getElementById().</p>

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



</body>
</html>

getElementsByName

No comments:

Post a Comment