javascript - 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>
解决方案
希望这可以帮助
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>
推荐阅读
- c# - 当我尝试使用 List<> 反序列化对象时出现异常
- angular - 角度 CDK 叠加限制位置范围
- python - 这个 jinja 变量赋值有什么问题?
- python - 在“__init__.py”Google 自定义搜索 API 中找不到参考“发现”
- python - 将相同的字典键映射到 Python 中的不同值
- node.js - 有没有一种方法可以让我在nodejs,expressjs中访问请求之外的请求参数
- c++ - 使用 std::transform 构造一个 std::vector。返回未命名结果的可能性?
- php - 阻止 Web 可执行文件类型在特定目录中运行?
- java - 在到达控制器之前和离开控制器之后解密/加密有效载荷
- javascript - 正则表达式以相同的字符开头和结尾