简体   繁体   中英

Uncaught TypeError: Cannot call method 'hasAttribute' of undefined

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.

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM