document.body.insertBefore不起作用

document.body.insertBefore doesn't work

本文关键字:不起作用 insertBefore body document      更新时间:2023-09-26

在下面的html页面中,我尝试将script2放在页脚之前。但这行不通。怎么了?

<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>scrollLeft demo</title>
  <script src="https://code.jquery.com/jquery-1.10.2.js"></script>
  <script>
    var script2 = document.createElement('script');
    script2.text="alert('ΟΚ')";
    document.body.insertBefore( script2, document.getElementsByClassName('footer'));
  </script>
</head>
<body>
<div class="demo"><h1>lalala</h1><p>Hello</p></div>
<div class="footer"><p>hello</p><p>world</p></div>
</body>
</html>

我也试过

 document.head.appendChild(script2); 

 document.body.appendChild(script2);

不起作用!

问题是,文档。Body还没有定义,当javascript被解释时它还没有开始加载

这有几个问题。

首先需要确保在正确的时间运行javascript。在代码中,在读取body标签之前运行JS。相反,将<script>放在关闭的</body>标记之前。

insertBefore()函数也以newNodereferenceNode为参数。document.getElementsByTagName('footer')返回一个元素列表。相反,将其更改为document.getElementsByTagName('footer')[0]以返回列表中的第一个元素

好的,我找到了。这是正确的。我把它放在文档里了。按照Jaromanda X的建议,我按照Jackson的建议添加('footer')[0]:

$( document ).ready(function() {
   var script2 = document.createElement('script');
   script2.text="alert('ΟΚ')";
   document.body.insertBefore( script2, document.getElementsByClassName('footer')[0]);
});