简体   繁体   中英

Find all div's beginning with id="string", iterate through result and change their id's

I have a button which creates div's with numbered id's (div0, div1, div2). Each div contains a button to delete the div. The buttons are also numberes (delete_div0, delete_div1, delete_div2).

After delete eg div0, I want to reorganize everything so it starts from 0 again (in this case div1 -> div0 and div2 -> div1.

Another example: Delete div1, div0 -> div0, div2 -> div1.

Any help?

 var counter_div = 0; $("#add_div").click(() => { $("#divs").append("<div id='div" + counter_div + "'>Div " + counter_div + " <button id='delete_div" + counter_div + "' type='button'>X</button></div>"); //add listener $("#delete_div" + counter_div).click((event) => { nr = event.target.id.substring( event.target.id.length - 1, event.target.id.length ); $("#div" + nr).remove(); }) // this is where I am struggling reorganizing divs function reorganize() { $("div[id^=div]").each((element) => { $(this).prop("id", "div" + element); }); } reorganize(); counter_div++; });
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <button id='add_div' type='button'>Add div</button></div> <div id='divs'></div>

EDIT: Thanks to everbody, I found a mix out of every solution.

$("#delete_div" + counter_div).click((event) => {
    //remove div
    $(event.currentTarget).parent().remove();

    //reorder all ingredients
    $("div[id^=div]").each((element) => {
        $(this)
        .find("div[id^='div']")
        .eq(element)
        .prop("id", "div" + element);
    };
});

Probalby not the most beautiful solution, but it works. What I did not understand yet is why $(this) in the each-function gives different results depending on which syntax I use.

$("div[id^=div]").each(function(element) {console.log($(this))};

is different to

$("div[id^=div]").each((element) => {console.log($(this))};

You can perform delete with $(event.currentTarget).parent().remove();.

Similarly if you want to select any input from on such button click you can use $(event.currentTarget).parent().find("input") .

Or you want to loop over divs and find all inputs then you can use :

$('#divs > div[id^=div]').each(function(k) {
    var allInputs = $(this).find('input');
});

 var counter_div = 0; $("#add_div").click(() => { $("#divs").append("<div id='div" + counter_div + "'>Div " + counter_div + " <button id='delete_div" + counter_div + "' type='button'>X</button></div>"); //add listener $("#delete_div" + counter_div).click((event) => { $(event.currentTarget).parent().remove(); }) counter_div++; });
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <button id='add_div' type='button'>Add div</button></div> <div id='divs'></div>

First call your reorganize on remove

    $("#div" + nr).remove();
      reorganize();
  })

then:

   var numDivsNum=-1;
//set first id -1
  function reorganize() {
    [...document.querySelectorAll("#divs > div[id^='div']")].forEach(el => {      
      el.id="div"+(++numDivsNum);
// for each element add new id +1
      el.innerHTML=el.innerHTML + "New id= " +numDivsNum;
    });

  }

And your selector was wrong, it should be:

div[id^='div']

not

div[id^=div]

 var counter_div = 0; $("#add_div").click(() => { $("#divs").append("<div id='div" + counter_div + "'>Div " + counter_div + " <button id='delete_div" + counter_div + "' type='button'>X</button></div>"); //add listener $("#delete_div" + counter_div).click((event) => { nr = event.target.id.substring( event.target.id.length - 1, event.target.id.length ); $("#div" + nr).remove(); reorganize(); }) // this is where I am struggling reorganizing divs var numDivsNum=-1; function reorganize() { [...document.querySelectorAll("#divs > div[id^='div']")].forEach(el => { el.id="div"+(++numDivsNum); el.innerHTML=el.innerHTML + "New id is id='div" +numDivsNum+"'"; }); } counter_div++; });
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <button id='add_div' type='button'>Add div</button></div> <div id='divs'></div>

You can re-index them like this:

$('div[id^="div"]').each(function(k) {
    $(this).prop('id', 'div' + k);
});

But personally I'd give them all a class so you don't have to rely on the begins with div selector, and then consider using data-id instead of id. data-id will be easier to extract as an integer later and that appears to be your goal. Maybe something like this?

$('div.my_class').each(function(k) {
    $(this).data('id', k);
});
$("#delete_div" + counter_div).click((event) => {
    //remove div
    $(event.currentTarget).parent().remove();

    //reorder all ingredients
    $("div[id^=div]").each((element) => {
        $(this)
        .find("div[id^='div']")
        .eq(element)
        .prop("id", "div" + element);
    };
});

你已经快完成了 但有些东西需要修复

$(this).parent('div').eq(0).remove();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM