Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

224
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda