javascript - Update DOM reference in jQuery each -
i modifying elements innerhtml
property inside $.each()
loop. if stack of elements contains childrens of element update innerhtml
, dom reference of children lost.
example:
$(function(){ $stack = $(".myelement, .myelement *"); $stack.each(function(){ var $this = $(this); var element = $(this)[0]; console.log(element.innerhtml = element.innerhtml + " modified"); }); });
fiddle: https://jsfiddle.net/b0ux0v5e/
what happens first modify innerhtml
of .myelement
. includes children p
. therefore dom reference of element lost , "modified" not appended.
how can such scenario solved without building function creates unique selector element , re-catches in each loop?
note: not asking appending text nodes. example. in real project replacing text in innerhtml
.
don't modify innerhtml, destroy/recreate elements inside , force re-render. can use insertadjacenthtml or jquery's append add element.
also not need do:
element = $(this)[0];
this
reference element.
$(function(){ $stack = $(".myelement, .myelement *"); $stack.each(function(){ var $this = $(this); //this.insertadjacenthtml("beforeend"," modified"); //or $this.append(" modified"); }); });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <div class="myelement"> <span>a span</span> <div>a div</div> <div> <p>a paragraph in div</p> </div> </div>
edit
as seems want replace word(s) , not append word, replace
on html , reset it, again destroy/recreate elements inside, if of them have event listeners attached lost
var modified = $".myelement").html().replace(/yourword/g,"modified"); $(".myelement").html(modified);
or loop on text nodes , replace word there, keep elements, event listeners, , on intact.
$(".myelement, .myelement *").contents().filter(function() { return this.nodetype == 3; }).each(function(){ this.textcontent = this.textcontent.replace(/a/g,"modified"); });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <div class="myelement"> inside element <br> <span>a span</span> <div>a div</div> <div> <p>a paragraph in div</p> </div> </div>
Comments
Post a Comment