Prototype.js, setStyle, and IE not working together

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.

JavaScript:
  1. var brDiv = document.createElement('div');
  2. 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.

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

Did that and it worked without a hitch.

This entry was posted in Programming and tagged , , , . Bookmark the permalink.

One Response to Prototype.js, setStyle, and IE not working together

  1. Nick says:

    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’});

Leave a Reply

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

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>