views:

363

answers:

3

Hi, I am trying to execute the following code from a firefox extension but it is not working. The actual code inside the else part was different but even this simple for loop is not getting executed. alert box without the for loop is working. Can someone have any idea about why this is not working. Thanks

window.addEventListener("pageshow",function(e)
    {
     if((document.title.trim()=="Mozilla Firefox") ||
        (document.title.trim()=="New Tab"))
     {
     }
     else
     {
      for(i=0;i<3;i++)
      {
       alert("hi");
      }
     }
    },true);
+1  A: 

If it's inside a Firefox extension, try using content.document instead of just document.

EDIT:

var metaTags = content.document.getElementsByTagName("meta");

for(var i = 0; i < metaTags.length; i++) {
    // do something with metaTags[i]
}

Also, if it helps, feel free to look through the source of any of the extensions I've written.

Chris Doggett
Hi Chris, actually document.title is working and I was using content.document for accessing the elements. but I was trying to loop through the meta tags but for some reason,loops are not working.Thanks for ur reply
Felix
A: 

document.title.trim()

Are you sure that's what you want? String->trim() is a non-standard JavaScript method so far only available in Firefox 3.1.

bobince
Yeah, document.title.trim() is working properly but loops are not working :(. Even the above code was not working. Its a simple for loop.
Felix
A: 

Hi, I Changed the for loop for...in loop and it worked :)

Felix
for..in is the wrong type of loop to use for simple linear arrays. I don't know what's going on here without the entire code, but a “for(var i=0;i<n;i++)” is the usual way for doing a simple loop. The “var” is important to avoid accidentally overwriting a global ‘i’ var.
bobince
Run this in a blank FF window by pasting it in the address bar to see the problem with for...in in javascript:javascript:var s = ""; var head = document.getElementsByTagName("head"); for(var i in head) { s += i + "\n"; } alert(s);I get:0lengthitemnamedItem
Chris Doggett
The point being, you get additional items you may not be expecting. The "for(var i = 0; i < n; i++)" doesn't get those extra items. I believe the "for...in" loop treats the array as an associative array and gets all of its properties.
Chris Doggett