我正在尝试将复选框附加到超链接的父元素(即段落)。由于某种原因,它不起作用。为什么?
<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>
答案 0 :(得分:3)
希望这会有所帮助
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>
答案 1 :(得分:1)
尝试
<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);
}