简体   繁体   中英

Why would this javascript not work in IE7 or Safari?

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/">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?

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/">Some Text</a></li>' + ul.innerHTML;
}
</script>

是的,在文档加载完成之前,IE无法访问DOM元素。

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/">Some Text</a></li>');
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM