Home > Software engineering >  How to remove some children html element and loop through parents to show remaining elements
How to remove some children html element and loop through parents to show remaining elements

Time:12-22

I want to find all available div.finput parents and loop through them, then remove the div.fsetting children and leave the div.form-group element and append it to the result wrapper with div.result.

How can I achieve this?

(($) => {
  generateForm()
})(jQuery);

function generateForm() {
  $(document).on('click', '.js-generate', function(e) {
    let elementRows = $('.finput');
    // alert(elementRows.length)
    let html = '';

    $.each(elementRows, function(i, v) {
      html  = elementRows.html();
    });

    $('.result').html(html);
  })
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<div >
  <div >
    <button >edit</button>>
  </div>
  <div >
    <input type="text" name="firatname" id="firstname">
  </div>
</div>
<div >
  <div >
    <button >edit</button>>
  </div>
  <div >
    <input type="email" name="email" id="email">
  </div>
</div>

<button >generate</button>
<div ></div>

The appended element in div.result should look like this:

<div >
  <div >
    <input type="text" name="firstname" id="firstname">
  </div>
  <div >
    <input type="email" name="email" id="email">
  </div>
</div>

CodePudding user response:

To create the HTML in your output example you can select the .form-group children of the .finput elements and append() them to .result. Then you can remove() the original .finput elements completely.

(($) => {
  generateForm()
})(jQuery);

function generateForm() {
  $(document).on('click', '.js-generate', function(e) {
    let $fInputs = $('.finput').remove();
    let $formGroups = $fInputs.children('.form-group');

    $('.result').append($formGroups);
  })
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div >
  <div >
    <button >edit</button>
  </div>
  <div >
    <input type="text" name="firatname" id="firstname">
  </div>
</div>
<div >
  <div >
    <button >edit</button>
  </div>
  <div >
    <input type="email" name="email" id="email">
  </div>
</div>

<button >generate</button>
<div ></div>

Also note that the (($) => {})(jQuery) structure you're using is an IIFE, not a document.ready event handler. The code is fine in this case as you're using a delegated event handler, however there's a meaningful difference between the two which may cause you issues if you're not aware of it.

  • Related