Ошибка типа, отображаемая в консоли
Это (файл Java-скрипта), для которого я получил ошибку типа
//GETELEMENTBYID
// Accessing the H1 tag dynamically and changing the colour
var ht = document.getElementById('hd1');
ht.style.color='white';
ht.style.backgroundColor='grey';
//Changing the text of the contents
var p1 = document.getElementById('para1');
p1.innerText='Java Script is kinda tough';
/* GETELEMENTSBYCLASSNAME
Changing the colour of list items */
var list = document.getElementsByClassName('list1');
console.log(list);
list[0].style.backgroundColor='gray'; // We have to specifically mention the item index for styling, else it'd show error.
for(var i = 0 ; i<= list.length; i++){
list[i].style.color='white';
}
Внутри цикла for в строке кода [21] отображается ошибка, которую я прикрепил к изображению. Любая помощь будет принята с благодарностью.
2 ответа
Массивы начинаются с 0. Array.length — это удобочитаемая форма длины.
Итак, arr = [0,1,2, 3,4]
имеет длину 5. Но arr[5]
находится за пределами поля. В цикле for вы выполняете цикл до i<=arr.length
, что дает вам неопределенное значение. Удалите =
, чтобы зациклить все элементы и не более того.
При работе с массивами обычно используется i < длина массива. Однако, если вы предпочитаете сохранить знак «=». Вы можете сделать я <длина массива - 1 :)
//GETELEMENTBYID
// Accessing the H1 tag dynamically and changing the colour
var ht = document.getElementById('hd1');
ht.style.color='white';
ht.style.backgroundColor='grey';
//Changing the text of the contents
var p1 = document.getElementById('para1');
p1.innerText='Java Script is kinda tough';
/* GETELEMENTSBYCLASSNAME
Changing the colour of list items */
var list = document.getElementsByClassName('list1');
console.log(list);
list[0].style.backgroundColor='gray'; // We have to specifically mention the item index for styling, else it'd show error.
for(var i = 0 ; i < list.length; i++){
list[i].style.color='white';
}
Код теперь должен работать :D
Похожие вопросы
Новые вопросы
typeerror
Ошибка TypeError - это определенный тип ошибки, возникающей при применении операции или функции к объекту неподходящего типа. Вы можете столкнуться с этим в Python или JavaScript.