David Crane
David Crane

Reputation: 93

Why does Script Console to Edit DOM Work in FireFox but not IE 11?

I'm having some issues editing the DOM in IE using console scripts.

In Firefox I can enter into the console

var divs = document.getElementsByTagName("div");
for(var i = 0; i < divs.length; i++){
   divs[i].style = "display:block";
}

and all divs on the page are given the appropriate block styling.

However the same script in my IE11 console has no effect on the DOM, and reports back "display:block" to the console. I know that the code is finding the divs, because I can put a console.log() in the loop and identify each div.

So what's going on? I'm utterly baffled why nothing happens, and all of my searches on using the f12 Developer Tools for IE make no mention of Javascript not working. In fact, the documentation says

The console not only displays output from code, but provides an interface to execute code as well. Just enter any valid JavaScript at the bottom of the Console, in the command line pane.

Upvotes: 1

Views: 72

Answers (1)

T.J. Crowder
T.J. Crowder

Reputation: 1074168

The style property on elements is not a string, it's an object. If browsers are allowing you to assign a string to it and handling that correctly, well, they're doing you a favor. :-) (They do us all favors like that, now and then.)

Instead, assign to the style object's display property:

divs[i].style.display = "block";

That's reliable, cross-browser. The only thing that could override it would be an !important rule in your CSS, which presumably you don't have.

If you really want to completely replace the style information on the elements (rather than just setting display to block), you can do that, via setAttribute:

divs[i].setAttribute("style", "display: block");

That's also reliable cross-browser. It wipes out any other inline styles on the element, replacing them with just that one.

Upvotes: 2

Related Questions