1

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

Alex
  • 1,060
  • 2
  • 17
  • 35

3 Answers3

2

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

alfonsob
  • 635
  • 1
  • 6
  • 16
0

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

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

JSfiddle

Community
  • 1
  • 1
Praveen
  • 55,303
  • 33
  • 133
  • 164
0

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.
  })
pixel 67
  • 1,530
  • 18
  • 22