Pergunta

Eu estou tentando criar uma matriz de <li> que estão em um div. Então, eu tenho

var arr = document.getElementById('mainNav').getElementsByTagName('li');

Para fins de teste, eu coloquei um alert("test"); alert(arr.length); para ver se um alerta irá aparecer e que o tamanho da matriz é. Nenhum dos alertas apareceu, mas se eu colocar um alerta antes que a declaração variável, ele funciona bem. O que poderia estar acontecendo de errado?

Foi útil?

Solução

Perhaps your alerts aren't showing up because document.getElementById('mainNav') is returning null. Check if you're getting a Javascript error. Or break up your code into multiple lines to make it easier to see where the error is occuring:

var mainNav = document.getElementById('mainNav');
alert(mainNav);
var arr = mainNav.getElementsByTagName('li');

Outras dicas

If you are sure that you have the LI elements within "mainNav". Try to put your code in the onLoad function:

window.onload = function(){
var arr = document.getElementById('mainNav').getElementsByTagName('li');

}

Your code maybe executing before the element is created.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top