1
I am using javascript to make a label and an input type text appear after selecting one of the radioButtons of my code, which in case are two, and if one is selected, the other automatically disappears.
The code is working perfectly, the problem is that an error appears in the browser console that is giving me a toc, and if it is appearing it is because it may generate a problem in the future...
Error: index.html:44 Uncaught Domexception: Failed to execute 'removeChild' on 'Node': The Node to be Removed is not a Child of this Node. At Htmlinputelement.cpf_option.onclick
Source code:
<!DOCTYPE html>
<html lang="pt-br">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
<div id="DivPrincipal">
<label>CPF</label>
<input type="radio" name="cpf_cnpj_options" value="CPF" id="cpf_options">
<label>CNPJ</label>
<input type="radio" name="cpf_cnpj_options" value="CNPJ" id="cnpj_options">
</div>
<script>
var radionButtons = document.getElementsByName("cpf_cnpj_options")
var cpf_option = document.querySelector("#cpf_options");
var cnpj_option = document.querySelector("#cnpj_options");
var label_cpf = document.createElement("label");
label_cpf.innerHTML = "CPF";
var input_cpf = document.createElement("input");
var attrPlaceHolderCpf = document.createAttribute("placeholder");
attrPlaceHolderCpf.value = "CPF";
input_cpf.setAttributeNode(attrPlaceHolderCpf);
var label_cnpj = document.createElement("label");
label_cnpj.innerHTML = "CNPJ";
var input_cnpj = document.createElement("input");
var attrPleaceHolder = document.createAttribute("placeholder");
attrPleaceHolder.value = "CNPJ";
input_cnpj.setAttributeNode(attrPleaceHolder);
cpf_option.onclick = function () {
for (let index = 0; index < radionButtons.length; index++) {
if (radionButtons[index] == cpf_option) {
document.getElementById("DivPrincipal").appendChild(label_cpf)
document.getElementById("DivPrincipal").appendChild(input_cpf)
}
}
document.getElementById("DivPrincipal").removeChild(label_cnpj)
document.getElementById("DivPrincipal").removeChild(input_cnpj)
}
cnpj_option.onclick = function () {
for (let index = 0; index < radionButtons.length; index++) {
if (radionButtons[index] == cnpj_option) {
document.getElementById("DivPrincipal").appendChild(label_cnpj)
document.getElementById("DivPrincipal").appendChild(input_cnpj)
}
}
document.getElementById("DivPrincipal").removeChild(label_cpf)
document.getElementById("DivPrincipal").removeChild(input_cpf)
}
</script>
</body>
</html>
I wasn’t getting the divPrincipal element, but now it worked. And by the way, your reply was very thorough, helped me understand more about how JS works in relation to HTML.
– Amystherdam