tags:

views:

178

answers:

3

Firefox handles it fine, but Safari and IE7 silently fail and do not insert the element.

<script type="text/javascript">
  var ul = document.getElementById('xg_navigation').getElementsByTagName('ul')[0];
  ul.innerHTML = '<li id="xg_tab_home" class="xg_subtab"><a href="http://somedomain.com/"&gt;Some Text</a></li>' + ul.innerHTML;
</script>

This is with an exisitng html structure like:

<div id="xg_navigation">
  <ul>
    <li><a href="...">Foo</a></li>
    ...
  </ul>
</div>

I dont have control over the HTML, but I do have the ability to insert a snippet of javascript in the page body.

Sadly I appear to be poorly educated on cross browser javascript support. Do I need to hook it it up via an onPageLoad sort of event somehow?

+2  A: 

Yes, IE cannot access DOM elements until the document load is complete.

palehorse
Then what is the proper way to set a fucntion to be run when the page is done loading that works cross browser?
Squeegy
As suggested by Luca, you use the window.onload event to catch when the DOM is ready.
Chuck
+6  A: 

Seems like you are manipulating the DOM before it has been loaded, try adding that snippet of code inside the window.onload listener:

<script type="text/javascript">
window.onload = function() {
    var ul = document.getElementById('xg_navigation').getElementsByTagName('ul')[0];
    ul.innerHTML = '<li id="xg_tab_home" class="xg_subtab"><a   href="http://somedomain.com/"&gt;Some Text</a></li>' + ul.innerHTML;
}
</script>
Luca Matteis
+1  A: 

Usually you have to wait for the DOM to be ready to execute a script that modifies the DOM.

An easy way to do that is to use jQuery:

$(function() { 
    $('#xg_navigation ul').prepend('<li id="xg_tab_home" class="xg_subtab"><a href="http://somedomain.com/"&gt;Some Text</a></li>');
});
grammar31