Reputation: 1185
I'm trying to append checkboxes to the parent elements of the hyperlinks (i.e. 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>
Upvotes: 0
Views: 780
Reputation: 282
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>
Upvotes: 2
Reputation: 159
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);
}
Upvotes: 1