Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

226
Visualizações
Elemento principal indefinido

Todavía estoy aprendiendo JS y estoy tratando de crear una validación de formulario. Me gustaría pintar el elemento principal de mi botón de opción <p> si el botón de opción no es válido.

Encontré una propiedad para ubicar el parent de mi HTMLElement : element.parentElement

Sin embargo, no puedo seleccionar el elemento <p> usando radio.parentElement . Aquí está mi código simplificado:

 window.onload = Init; function Init() { var formElement = document.forms.myform; //myform var radio = formElement.radioName; formElement.onsubmit = ProcessForm; var isFormValid = () => { //validate if form is valid if not -> paint <p> red if ( radio.value === null || radio.value === "" ) { console.log(radio.parentElement); //(this is undefined. Why?) radio.parentElement.backgroundColor = "red"; //(this does not work because it is undefined) //Error:doubt.js:13 Uncaught TypeError: Cannot set properties of undefined (setting 'backgroundColor') return false; } return true; }; function ProcessForm(event) { event.preventDefault(); if (isFormValid()) { //do stuff } else { //do nothing } } }
 <!DOCTYPE html> <html> <head> <script src="./doubt.js"></script> </head> <body> <form name="myform" action="#" method="POST"> <p id="caption_project"> Project Selection <br /> <input type="radio" name="radioName" id="id1" value="1" /> <label for="id1">1</label> <br /> <input type="radio" name="radioName" id="id2" value="2" /> <label for="id2">2</label> <br /> </p> <input id="btnSubmit" type="submit" /> </form> </body> </html>

¿Cómo puedo seleccionar el elemento <p> sin cambiar el documento HTML?

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

Tiene más de una entrada de radio denominada radioName , por lo que formElement.radioName no es la entrada; es la colección de entradas. Puede obtener la enésima entrada especificando su índice, como formElement.radioName[0] .

 var formElement = document.forms.myform; //myform var radio = formElement.radioName; // first radio console.log(radio[0].parentElement);
 <form name="myform" action="#" method="POST"> <p id="caption_project"> Project Selection <br /> <input type="radio" name="radioName" id="id1" value="1" /> <label for="id1">1</label> <br /> <input type="radio" name="radioName" id="id2" value="2" /> <label for="id2">2</label> <br /> </p> <input id="btnSubmit" type="submit" /> </form>

También puede simplemente consultar la p a través de querySelector :

 // query the document for the id: console.log(document.querySelector('#caption_project')); // or the first p under the form: console.log(document.forms.myform.querySelector('p'));
 <form name="myform" action="#" method="POST"> <p id="caption_project"> Project Selection <br /> <input type="radio" name="radioName" id="id1" value="1" /> <label for="id1">1</label> <br /> <input type="radio" name="radioName" id="id2" value="2" /> <label for="id2">2</label> <br /> </p> <input id="btnSubmit" type="submit" /> </form>

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda