Javascript: how to get text nodes following/preceding break tags and wrap them with ddb tag? -


i have accomplished in jquery implementation in javascript without dependence on libraries.

$("br",document).parent().contents().each(function() {     var text = this.textcontent ? this.textcontent : this.innertext;     text = this.textcontent.replace(/\s+/g, '')     if ( this.nodetype == 3 && text.length != 0) {         $(this).wrap('<ddb></ddb>')     } }); 

the following code should exact same thing function does.

<html>  <body> hello <p> hello <br/> hello 2 <br/>       <br/>       <br/> </p>  <button onclick="wraptext()">wrap</button>  <script type="text/javascript">     function wraptext() {         var nodelist = document.getelementsbytagname('br');         (var i=0; < nodelist.length; i++) {             var node = nodelist[i];             var parentnode = node.parentnode;             if (!parentnode) continue;             (var c=0; c < parentnode.childnodes.length; c++) {                 var child = parentnode.childnodes[c];                 if (child.nodetype != 3) continue;                  if (child.nodevalue.match(/[^\s]/) != null) {                     var newelement = document.createelement("b");                     newelement.innerhtml = child.nodevalue;                     parentnode.insertbefore(newelement, child);                     parentnode.removechild(child);                 }             }         }     } </script>  </body> </html> 

however, should point out if <br/> wrapped in element, getting childnodes of that element, if simple <b> tag wrap text nodes inside <b> <ddb></ddb> (what that, way?).

you had bug assigning text node.textcontent ? node.textcontent : node.innertext next line used node.textcontent, fixed that. changed regex match first non-whitespace character, , if did find one, wrapped it.


Comments

Popular posts from this blog

asp.net - repeatedly call AddImageUrl(url) to assemble pdf document -

java - Android recognize cell phone with keyboard or not? -

iphone - How would you achieve a LED Scrolling effect? -