未捕获的类型错误:无法读取未定义的属性(读取'parentNode')

4

我已经将以下脚本添加到我的网页中,当用户进行newsletter注册时会触发。我想在用户订阅后显示一些自定义内容。

<script>
  function insertAfter(referenceNode, newNode) {
  referenceNode.parentNode.insertBefore(newNode, referenceNode.nextSibling);
}

    var news = document.getElementsByClassName("et_pb_newsletter_success")[0].selectedIndex;
    var text = document.createTextNode("Thank you for joining our SOS Family! We are very grateful to have you with us. Thanks to compassionate people like you, SOS is meeting needs and improving the lives of our friends and neighbours in District 69. You can expect valuable emails from us on a regular basis, and you can unsubscribe at any time.");
    var learn = document.createTextNode("Learn more about SOS.")
  insertAfter(news,text);
  insertAfter(text,learn);
  
  var img = document.createElement("img");
  img.src = "https://sosd69.com/wp-content/uploads/newsletter_success.jpeg";
    
  insertAfter(learn,img);

    let btn = document.createElement("button");
    btn.innerHTML = "Watch Video";
    btn.onclick = function () {
        window.location='https://www.youtube.com/watch?v=OcYyhazCiHs';
    };
    btn.classList.add("et_pb_button_0");
  insertAfter(img,btn);
</script>

我收到了以下控制台错误:

Uncaught TypeError: Cannot read properties of undefined (reading 'parentNode')
    at insertAfter ((index):666)
    at (index):672

我创建的insertAfter函数是否存在错误?也许问题是脚本在"et_pb_newsletter_success"类被创建之前加载,当用户点击订阅按钮时。非常感谢您提供任何见解!


1
除了下面回答者处理的gEBCN问题之外,还存在一个逻辑错误,新创建的文本节点尚未插入到任何元素中,因此它们无法具有父节点。 - Teemu
谢谢!在这种情况下,我该如何将新创建的文本节点附加到 et_pb_newsletter_success 类中的元素上? - AC1
1个回答

0

getElementsByClassName - 返回一个数组,因此您需要从该数组中获取项目并使用它。

var news = document.getElementsByClassName("et_pb_newsletter_success")[0];

抱歉!看起来我发布的代码没有更新,但是我确实有那个索引HTML数组的行。错误仍然发生。我已经编辑了问题以显示更新后的代码。 - AC1
这个 selectedIndex 是什么?它没有这样的属性,所以它失败了。放一个调试器并检查你传递给 insertAfter() 的值是什么。如果你删除 ".selectedIndex",我猜它会工作。 - Jibin.Jay
删除.selectedIndex会导致以下错误:Uncaught DOMException: Failed to execute 'appendChild' on 'Node': This node type does not support this method. at HTMLDocument.<anonymous> (https://sosd69.com/contact-sos/:670:10) at e (https://sosd69.com/wp-includes/js/jquery/jquery.min.js?ver=3.6.0:2:30038) at t (https://sosd69.com/wp-includes/js/jquery/jquery.min.js?ver=3.6.0:2:30340) - AC1
尝试将您的代码添加到CodePen/JSFiddle等网站,并在问题中发布。这样我们就可以更轻松地帮助您了。 - Jibin.Jay

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接