javascript - Jquery : Changing the last div's content id without reflecting changes to previous one -
i have 1 div who's id xyz1
, inside has 3 div who's id abc1
,def1
,ghi1
respectfully. when user click on add new
button current div xyz1
should cloned , hidden , cloned div appended below xyz1
div . , new cloned div having parent id xyz2
, children div's should have id abc2
,def2
,ghi2
. following code should make more sense .
<div id="xyz1" style="display:block"> <div id="abc1" class="abc"></div> <div id="def1" class="def"></div> <div id="ghi1" class="ghi"></div> </div>
when user click on add new
button div should hide , next div should below .
<div id="xyz2" style="display:block"> <div id="abc2" class="abc"></div> <div id="def2" class="def"></div> <div id="ghi2" class="ghi"></div> </div>
important: previous div's id number should not modified .
what did
var $cloned_div = $("#xyz1").clone().prop("id","xyz2"); $($cloned_div).appendto("div:last"); $("#xyz2").each(function(){ $(".abc").prop("id","abc2"); $(".def").prop("id","def2"); $(".ghi").prop("id","ghi2"); });
this working fine second div , prop()
method getting applied previous 1 also. means previous div's id reflected too.
this how becomes
<div id="xyz1" style="display:block"> <div id="abc2" class="abc"></div> <div id="def2" class="def"></div> <div id="ghi2" class="ghi"></div> </div> <div id="xyz2" style="display:block"> <div id="abc2" class="abc"></div> <div id="def2" class="def"></div> <div id="ghi2" class="ghi"></div> </div>
and don't want change class name because many dependencies in code class .
in html last div visible , can select jquery :visible
selector. after finding visible div, should index of id of regex can work. when find last div , index index, copy using .clone()
, change id attribute of cloned elements. @ end, insert copied element after last div .insertafter()
, hide old div.
$("button").click(function(){ // selecte div visible var div = $("[id^='xyz']:visible"); // id of target div var id = parseint(div.attr("id").match(/\d+/))+1; // copy target div , change id of , childs , insert new div after old div. div.clone().attr("id", "xyz"+ id) .find(".abc").attr("id", "abc"+ id).end() .find(".def").attr("id", "def"+ id).end() .find(".ghi").attr("id", "ghi"+ id).end() .insertafter(div); // hide target div div.hide(); });
$("button").click(function(){ var div = $("[id^='xyz']:visible"); var id = parseint(div.attr("id").match(/\d+/))+1; div.clone().attr("id", "xyz"+ id) .find(".abc").attr("id", "abc"+ id).end() .find(".def").attr("id", "def"+ id).end() .find(".ghi").attr("id", "ghi"+ id).end() .insertafter(div); div.hide(); console.log($("[id^='xyz']:visible")[0].outerhtml); });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <button>add new</button> <div id="xyz1" style="display:block"> <div id="abc1" class="abc"></div> <div id="def1" class="def"></div> <div id="ghi1" class="ghi"></div> </div>
Comments
Post a Comment