Posted by & filed under Programming.

Sometimes IE just irritates me. Ok, pretty much anytime I’m working on a web site. Especially when it involves Javascript or DOM.

For the past couple of hours I’ve been scouring the internet looking for a solution to the prototype method setStyle not working in IE8. I was getting an ‘Object does not support this method’ when trying to use setStyle on a newly created div.

Here’s the code that was causing the problem.

var brDiv = document.createElement('div');
brDiv.setStyle({ backgroundColor: 'black', position: 'absolute'});

There was more to it, but that’s enough that it would throw the error.

After too many trials and errors to count, Google brought me to this page that had a working solution. The key was not to call setStyle on the object, but call it on Element and pass the object as a parameter.

var brDiv = document.createElement('div');
Element.setStyle(brDiv, { backgroundColor: 'black', position: 'absolute'});

Did that and it worked without a hitch.

2 Responses to “Prototype.js, setStyle, and IE not working together”

  1. Nick

    Prototype has to extend elements before you can call the new methods on them. When you dynamically create a div, it won’t yet be extended. You can use prototype’s $() function to quickly extend a new element.

    var brDiv = $(document.createElement(‘div’));

    brDiv.setStyle({ backgroundColor: ‘black’, position: ‘absolute’});

  2. npup

    When creating DOM elements one can as well use Prototype’s functions for it and get the extension from the start, even in IE, and set most of the stuff in one fell swoop:

    var brDiv = new Element('div', {id: 'cool_container', className: 'class0 class1'}).setStyle({backgroundColor: 'black', position: 'absolute'}); // it is extended from birth

    One semi-semi-related thing that happened to me recently was that all elements on the page seemed to be unextended on a page in IE. The source of the problem was that prototype.js was being included twice on the page. It blew IE away – not sure why yet. But there is some special stuff about extending the elements in IE for sure.



Leave a Reply

Your email address will not be published. Required fields are marked *