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);
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.