getElementsByClassName not finding uls

664 Views Asked by At

I am unable to get my code working correctly in Chrome however when I paste my code into JSFIDDLE it works correctly. I am trying to get all ul tags in the document using getElementsByClassName and then all lis within the one of the uls. When I use getElementsByClassName("ul") it is finding none in Chrome, however if I remove either one of the two divs before the uls getElementsByClassName("ul") finds all of them so the divs seem to be what is breaking the JS.

I was unable to reproduce the problem in JSFIDDLE as the code worked correctly there but here it is: http://jsfiddle.net/zTP9H/

var sElements = document.getElementsByClassName("HeaderWrapWide");
var catOne = document.getElementsByTagName("ul");
alert("number of ul: " + catOne.length);

var liTags = catOne[3].getElementsByTagName("li");
alert("number of li: " + liTags.length);

Thanks

Alex

3

There are 3 best solutions below

1
On BEST ANSWER

are you sure you are running this javascript AFTER the html is added to the page? jsfiddle probably renders html/scripts in a different way to your webpage and hence that is why it works there. If your javascript is in the head part of your HTML you could well have this behaviour - try using jquery on document ready function http://api.jquery.com/ready/ or move your JS to the bottom of the page

I cant see anything wrong with your code

0
On

I guess you have the above JS code within your head tag. So wrap it with Immediate function invocation

(function () {
   //ToDos
})();

JSfiddle

0
On

If you want to execute the code in the <head></head>
like you have it, then try wrapping your code in a
function like this if you don't want to use jQuery.
Also, this doesn't work in IE so check caniuse.com/#search=DOMContentLoaded

document.addEventListener('DOMContentLoaded', function() {
    your code here.
  })