Reputation: 135
I have a HTML page, source code is given below -
<html>
<script type="text/javascript">
function jsMeth() {
alert('Count of buttons : '+document.getElementsByTagName('button').length);
}
</script>
<input type="button" value="button 1" id="btn1" name="btn1" /><br>
<input type="button" value="butto 2" id="btn2" name="btn2" /><br><br>
<input type="button" value="Calculate button count" id="btn3" name="btn3" onclick="jsMeth();"/>
</html>
My basic purpose is, when I click on button having id "btn3", it should display number of buttons in my HTML page (in this case 3). But somehow it is always showing 0.
Thanks for your quick reply. As all of you suggested, I have modified my code as shown below -
<html>
<script type="text/javascript">
function jsMeth() {
alert('Count of buttons : '+document.querySelectorAll('[type=button]').length);
}
</script>
<input type="button" value="button 1" id="btn1" name="btn1" /><br>
<input type="button" value="butto 2" id="btn2" name="btn2" /><br><br>
<input type="button" value="Calculate button count" id="btn3" name="btn3" onclick="jsMeth();"/>
</html>
But now I am getting below error -
Message: Object doesn't support this property or method
Line: 4
Char: 9
Code: 0
URI: file:///C:/Documents%20and%20Settings/556996/Desktop/demohtml.html
I am testing in IE8. Please help!
Thanks, Kartic
Upvotes: 1
Views: 1962
Reputation: 2653
Use this...
function jsMeth() {
alert('Count of buttons : '+document.querySelectorAll('[type=button]').length);
}
Or this for old browsers
function jsMeth() {
var elem = document.getElementsByTagName('input');
var numBts = 0;
for(i = 0; i < elem.length; i++){
if(elem[i].getAttribute('type') === 'button'){
numBts+=1;
}
}
alert(numBts);
}
Upvotes: 1
Reputation: 27560
The problem you're facing is that you don't have any elements with the tag name button
. All of your buttons have the tag name input
.
If you aren't supporting IE7, you could use querySelectorAll
to get those elements:
document.querySelectorAll('input[type=button]')
Or you could change your HTML to use <button>
elements:
<button type="button" value="button 1" id="btn1" name="btn1">button 1</button>
Upvotes: 2
Reputation: 191789
Try using either of
document.getElementsByTagName('input')
or the more specific
document.querySelectorAll('[type=button'])
Upvotes: 3