Reputation: 67
I am trying to check if buttons has name attribute or not.The Following line is giving result correctly.
alert(course_view_buttons[30].hasAttribute("name"));
But the following code is giving an error like this-
"Uncaught TypeError: Cannot call method 'hasAttribute' of undefined "
The full code is here-
var course_view_buttons = document.getElementsByTagName("button");
alert(course_view_buttons.length);
var a=0;
for (x=0;x<=course_view_buttons.length;x++){
if(course_view_buttons[x].hasAttribute("name");){
a++;
}
}
alert(a);
Please help me if anyone can.I am stuck in this for 4-5 hours. Thanks in advance.
Upvotes: 0
Views: 437
Reputation:
The problem is testing for less than or equal to
in this expression:
x <= course_view_buttons.length
When x
is set to the value of course_view_buttons.length
in the final iteration of the loop, course_view_buttons[x]
references points to an element that doesn't exist. This is because array indexes start at 0, but length values start at 1.
The solution is to remove the equals sign:
x < course_view_buttons.length
Upvotes: 2
Reputation: 123739
Your for loop condition, change it to
for (x=0;x < course_view_buttons.length;x++){
^_________ There is no <= which will give undefined as you are out of array bounds.
Array index starts with 0.. length-1
So in your case for the last array iteration it tries to access
course_view_buttons[30].hasAttribute("name")
when course_view_buttons[30]
doesn't exist
Upvotes: 1