referenceNode.parentNode抛出undefined

时间:2015-04-03 02:39:41

标签: javascript jquery

我正在尝试使用JavaScript复制jQuery的after()

var orangeBlock = '<a href="http://clo2015.chineselearnonline.com/">Try out the New Version of CLO</a></div>'
var greyBlock = document.getElementsByClassName('grey-block')

function insertAfter(newNode, referenceNode) {
  console.log(referenceNode.parentNode)
  referenceNode.parentNode.insertBefore(newNode, referenceNode.nextSibling)
}

insertAfter(orangeBlock, greyBlock)

但我收到以下错误:

未捕获的TypeError:无法调用未定义的theme.js的方法'insertBefore':62 insertAfter theme.js:62 (匿名函数)

我觉得很奇怪,因为console.log(greyBlock)会输出项目:

[item: function]
0: div.grey-block
length: 1
__proto__: NodeList

直播网站:http://www.chineselearnonline.com/amember/member.php

2 个答案:

答案 0 :(得分:1)

orangeBlock是一个字符串。您需要一个DOM节点才能使用insertBefore。你可以像下面这样转换它。

var orange = document.createElement('div');
orange.innerHTML = orangeBlock;

document.getElementsByClassName获取节点列表。因此,您需要从中选择一个greyBlock[0]

最后这样的事情。

var orangeBlock = '<a href="http://clo2015.chineselearnonline.com/">Try out the New Version of CLO</a>';
var orange = document.createElement('div');
orange.innerHTML = orangeBlock;

var greyBlock = document.getElementsByClassName('grey-block');

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

insertAfter(orange, greyBlock[0]);

答案 1 :(得分:1)

好吧,你的insertAfter函数确实需要DOM节点! orangeBlock(字符串)和greyBlock(节点列表)都不是节点。

所以请做一些像

这样的事情
// create an element using DOM methods
var orangeBlock = document.createElement("a");
orangeBlock.href="http://clo2015.chineselearnonline.com/";
orangeBlock.appendChild(document.createTextNode("Try out the New Version of CLO"));
 // access the first element in the node list
var greyBlock = document.getElementsByClassName('grey-block')[0];

function insertAfter(newNode, referenceNode) {
  console.log(referenceNode.parentNode)
  referenceNode.parentNode.insertBefore(newNode, referenceNode.nextSibling)
}
if (greyBlock)
    insertAfter(orangeBlock, greyBlock)
else
    alert("could not find an element with the class 'grey-block'");

但实际上,您想要使用insertAdjacentHTML method

 document.getElementsByClassName('grey-block')[0].insertAdjacentHTML('afterend', '<a href="http://clo2015.chineselearnonline.com/">Try out the New Version of CLO</a>')