tags:

views:

201

answers:

4

Hi,

I've come across a problem when trying to loop through all divs on a page.

I can grab all the divs using $('div') in IE but not in firefox.

I did the following as a test :-

 $(function() {

        var divs = document.getElementsByTagName('div');

        alert(divs.length)

        var divs2 = $('div')

        alert(divs2.length)

 });

The output in IE is :-

29 29

The output in firefox is :-

29 1

Am I missing something?

A: 

What about var divs2 = $('div').length;

mgroves
A: 

$("div") creates new div element, that's why 1 ;)

Try: alert($("div").length);

usoban
$("div") doesn't create anything. $("<div>") creates a new element.
Sean Nyman
Oh you're right, it doesn't create new div, it creates something else, probably string. Still, it's a single object so that's why output is 1.
usoban
Yeah according to me $("div") should grab an array of all divs from the DOM. Which it does seem to be doing in IE but not in firefox
Well, I tried var div = $("div"); and then $("#somediv").append(div); and the output is text 'div'. I tried IE and FF, same result.
usoban
+1  A: 

Check your markup. With 29 divs, I bet you have a missing </div> or something somewhere. IE might just count the opening tag; perhaps FF is more strict.

Typeoneerror
Firefox, this page you're looking at now: $('div').length == 121. I also would suspect a markup problem, because what you're doing should work just fine, and does work on other pages
Joel Mueller
I think it was a problem with the DOM in the end, the problem seemed to be resolved after I wrapped some div tags around a asp.net content place holder in my master page.
A: 

I agree that you probably have a markup problem. If it's not that, make sure that you have Firebug - or anything else that might modify the DOM - turned off.

Chris B