Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

71
Views
jQuery agregar si no existe

Me gustaría agregar un div solo si aún no está allí. Estoy intentando con esto pero no funciona:

 $('#method_id').on('change', function (e) { if ($(this).find("option:selected").data('method-column-id') != 1) { if ($('#column_message').next('div').length) $('#column_message') .append('<div id="warning_message" class="alert alert-danger"><strong>Warning!</strong> Installed column and method do not match</div>'); } else { $('.form-group').find('#column_message>.alert').remove(); } });

Y si elimino la segunda cláusula if, se agrega cada vez que selecciono una opción que pasa primero la cláusula if

Aquí está el HTML

 <!-- Warning message --> <div class="form-group"> <label for="group" class="col-md-2 control-label"></label> <div id="column_message" class="col-md-6"> </div> </div>
about 4 years ago · Santiago Trujillo
3 answers
Answer question

0

Para verificar si existe un elemento, debe encontrar un selector que coincida solo con ese elemento y verificar si la longitud del objeto jQuery es igual a 0 o no, así:

 if ($('#unique-selector').length === 0) { // code to run if it isn't there } else { // code to run if it is there }
about 4 years ago · Santiago Trujillo Report

0

A medida que agrega div con id, puede buscar si ese div existe llamando:

 if($("#warning_message").length > 0 ){ $('.form-group').find('#column_message>.alert').remove(); }else{ $('#column_message').append('<div id="warning_message" class="alert alert-danger"><strong>Warning!</strong> Installed column and method do not match</div>'); }

Pero si desea tener más divisiones de alerta, puede buscar la clase "alerta" más o menos.

Otra forma sin identificación (probablemente mejor) sería usar el método children()

about 4 years ago · Santiago Trujillo Report

0

el if interno debería ser if ($('#column_message').next('div').length===0) o if(!$('#column_message').next('div').length)

about 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!