简体   繁体   English

Javascript:带有 AppendChild 的 DOM 异常错误

[英]Javascript: DOM Exception Error with AppendChild

Why i get an error ?为什么我收到错误? I just want to add 'a' to the div.我只想在 div 中添加“a”。 Not remplace, but add.不是替换,而是添加。

 var conteneur1 = document.getElementsByClassName('conteneur')[0]; conteneur1.appendChild('a');

I have: NotFoundError: DOM Exception 8: An attempt was made to reference a node in a context where it doesn't exist.我有: NotFoundError: DOM Exception 8: 尝试在不存在的上下文中引用节点。 Thanks for helping !感谢您的帮助!

You cannot just pass a string to appendChild() , you have to pass a node element.您不能只将字符串传递给appendChild() ,您必须传递一个节点元素。

The Node.appendChild() method adds a node to the end of the list of children of a specified parent node. Node.appendChild() 方法将一个节点添加到指定父节点的子节点列表的末尾。

var conteneur1 = document.getElementsByClassName('conteneur')[0];
var a = document.createElement('a');
conteneur1.appendChild(a);

So, I think it's not correct way to append child.所以,我认为附加孩子不是正确的方法。 Try the code below:试试下面的代码:

var anchorEl = document.createElement('a');
var textOfLink = document.createTextNode("YourText");

anchorEl.appendChild(textOfLink);
anchorEl.title = "YourLink";
anchorEl.href = "http://YourLink.com";

var conteneur1 = document.getElementsByClassName('conteneur')[0];
      conteneur1.appendChild(anchorEl);

What you are doing is simply passing a string as an argument .appendChild() does not accept string.您所做的只是将字符串作为参数传递。appendChild()不接受字符串。

this should fix it.这应该解决它。

    var conteneur1 = document.getElementsByClassName('conteneur')[0];
    var a = document.createElement('a');
    conteneur1.appendChild(a);

See here w3School请看这里w3School

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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