1
function func(){
    with (document.forms[0]){
        inputid.value = "text"; //Works!
        spanid.innerHTML = "text"; //Err, spanid is not defined.
    }
}

This is not working in Firefox but it is in IE7. I debug in Firebug, spanid is not defined, but I can use document.getElementById("spanid") to select this element. I just don't know why? The input element works fine!

etlds
  • 5,810
  • 2
  • 23
  • 30

2 Answers2

3

Shouldn't it be document.forms[0] (notice the s on form)

**EDIT**

Since the answers aren't rolling in on this one, here's my suggestion. Simply it. Use the methods you're familiar with and don't waste time trying to get this to work.

function YourFunction()
{
    var objSpan = document.getElementById([Insert Element ID]);
    var objInput = document.getElementById([Insert Element ID]);

    objSpan.InnerHTML = "text";
    ...
}
James Hill
  • 60,353
  • 20
  • 145
  • 161
  • I think that is why people don't suggest with() – etlds Jul 01 '11 at 16:50
  • 1
    @Desheng there are very few real needs for `with`. See http://stackoverflow.com/questions/61552/are-there-legitimate-uses-for-javascripts-with-statement – Matt Ball Jul 01 '11 at 17:12
0

IE sticks all elements with IDs as properties on the global scope. Firefox does not do that in standards mode (but does in quirks mode).

Boris Zbarsky
  • 34,758
  • 5
  • 52
  • 55
  • @Quentin Yes, but `document.forms[0]` doesn't get random divs hanging off it. Only some HTML elements end up with their id/name as properties on a `
    `, and `
    ` is not in that set.
    – Boris Zbarsky Jul 02 '11 at 00:52