首页 > 解决方案 > AppendChild 不适用于父元素

问题描述

我正在尝试将复选框附加到超链接的父元素(即段落)。由于某种原因,它不起作用。为什么?

<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>

标签: javascript

解决方案


希望这可以帮助

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>


推荐阅读