...

View Full Version : getElementBytagName



cicily
05-17-2012, 05:52 AM
By using this javascript method can we check an element with particular id is present or not?


<html>
<head>
<script type="text/javascript">
function getElements()
{
var x=document.getElementsByTagName("input");

for(i=0;i<x.length;i++)
{
if(x[i].id== x1)
{alert("its x1");}

else
{alert("notx1");
}
alert(x.length);
}
</script>
</head>
<body>

<input id="x1" type="text" size="20" /><br />
<input type="text" size="20" /><br />

<input type="button" onclick="getElements()" value="How many input elements?" />

</body>
</html>

Am a beginner in javascript;)

Philip M
05-17-2012, 09:21 AM
if(x[i].id== x1) // a literal must be in quotes "x1"



<script type="text/javascript">
function getElements() {
var x=document.getElementsByTagName("input");
alert(x.length);

for(i=0;i<x.length;i++) {
if(x[i].id== "x1") {
alert("input " + i + " is x1")
}

else {
alert("input " + i + " is not x1");
}
}

}
</script>

The way you have disposed your opening and closing braces is very confusing -
it is recomemnded that you place the opening brace following the function, if, else, for, while, do, switch, and try statements on the same line and not on the following line. Apart from that every Javascript statement should be followed by a semi-colon. ; It is quite possible to disregard this advice, but if you do one day it will rise up and bite you in the undercarriage.

BTW, when posting here please help us to help you by following the posting guidelines and wrapping your code in CODE tags. This means use the octothorpe or # button on the toolbar. You can (and should) edit your previous post.

cicily
05-25-2012, 07:10 AM
Thank u very much phil it helped.. :)



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum