[英]AppendChild doesn't work for parent element
I'm trying to append checkboxes to the parent elements of the hyperlinks (ie to paragraphs).我正在尝试将复选框附加到超链接的父元素(即段落)。 For some reason it doesn't work.
由于某种原因,它不起作用。 Why?
为什么?
<p><a href="https://example.com">Hyperlink</a></p>
<p><a href="https://example.org">Hyperlink</a></p>
<script>
var links = document.querySelectorAll('a');
var i;
for (i = 0; i < links.length; i++) {
var input = document.createElement('input');
input.setAttribute('type', 'checkbox');
// links[i].appendChild(input); // works
links[i].parentElement.nodeName.appendChild(input); // doesn't work
}
</script>
hope this helps希望这可以帮助
var links = document.querySelectorAll('a'); var i; for (i = 0; i < links.length; i++) { var input = document.createElement('input'); input.setAttribute('type', 'checkbox'); // links[i].appendChild(input); // works // doesn't work - links[i].parentElement.nodeName.appendChild is not a function" // links[i].parentElement.nodeName.appendChild(input); links[i].parentNode.appendChild(input); }
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>title</title> </head> <body> <div> <p><a href="https://example.com">Hyperlink</a></p> <p><a href="https://example.org">Hyperlink</a></p> </div> </body> </html>
try this尝试这个
<p><a href="https://example.com">Hyperlink</a></p>
<p> <a href="https://example.org">Hyperlink</a></p>
<script>
var links = document.querySelectorAll('a');
var i;
for (i = 0; i < links.length; i++) {
var input = document.createElement('input');
input.setAttribute('type', 'checkbox');
links[i].parentNode.appendChild(input);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.