When you're creating a new option element that will be added to a select element IE wants to do it one way while everyone else can handle it another way. I'll show the first way I tried to tackle it, and then show the cross browser way to handle it.
I set up a try, catch block that would try IE first. If an error occurred it would fall back to the second method that works in most browsers.
//IE code
try
{
obj_option = document.createElement('<option value="test value"/>');
obj_text = document.createTextNode("option text value");
obj_option.appendChild(obj_text);
}
//everyone else
catch(e)
{
var obj_option = document.createElement('option');
obj_option.text = "option text value";
obj_option.value = "test value";
}
Internet Explorer wants to place the value inside of the createElement method while other browsers can handle the assignment on the object property. Also IE wants the text added with createTextNode. It's a pain to have two methods for something so simple. After a bit of experimentation and research I have a method that works for all browsers.
var obj_option;
var obj_text;
obj_option = document.createElement('option');
obj_text = document.createTextNode("option text value");
obj_option.appendChild(obj_text);
obj_option.setAttribute("value", "test value");
This is much cleaner and easier to maintain. setAttribute is also a handy method for assigning non standard properties to an object. Some client-side form validation scripts want to add proprietary properties to a tag. Using setAttribute is the easiest way to create them.
3 comments:
If you found this page useful, or you have any feedback, please leave a comment.