html - Javascript wrap all text nodes in tags -
i know question has been asked of answers use wrap
function of jquery. i'm trying figure out plain javascript way of doing this:
<div id="content"> "hey" <br> <br> "foo" "bar" </div> <script> function mainfocusout(e) { //here or other focus outs...create function between <br> tags , put divs if (e == 'undefined') e = window.event; var target = e.target || e.srcelement; (var = 0; < target.childnodes.length; i++) { //i'm not sure if need closure function here inside loop works on each individual textnode (function(i) { var curnode = target.childnodes[i]; if (curnode.nodename === "#text") { var element = document.createelement("div"); element.appendchild(curnode); target.insertbefore(element, curnode); //notfounderror: failed execute 'insertbefore' on 'node': node before new node inserted not child of node. } })(i); } } </script>
of course desired output text nodes between div tags, same position. doing wrong? , simple have here, simple loop?
it seems me, need switch around these 2 lines:
element.appendchild(curnode); target.insertbefore(element, curnode);
so becomes:
target.insertbefore(element, curnode); element.appendchild(curnode);
because right now, append curnode new div, before placing div in correct position. results in:
<div>"hey"</div>
that's great, in order put div on right place, can not place before "hey"
anymore, since put inside div.
by swapping 2 lines, first place div in front of "hey"
:
<div></div>"hey"
and then position "hey" correctly inside div:
<div>"hey"</div>
i hope helps!
Comments
Post a Comment