Question

I need some small and compact so I've been doing so trials, I have something that is working slightly, just for some reason its not actually appending the new html...

 var a = document.querySelectorAll('.post .content div');
 var b = a[7].childNodes;
 for(i=0;i<b.length;i++){
  var exp = /(\b(https?|ftp|file):\/\/[\-A-Z0-9+&@#\/%?=~_|!:,.;]*[\-A-Z0-9+&@#\/%=~_|])/ig;
   if(b[i].nodeType === 3){
     var ahref = document.createElement('a');
         ahref.className="easyBBurlFetch";
         ahref.href=b[i].nodeValue.replace(exp,'$1');
         ahref.innerText=b[i].nodeValue.replace(exp,'$1');
     b[i].parentNode.insertBefore(ahref,b[i]);
     b[i].parentNode.removeChild(b[i]);
    }
  }

Testing Fiddle

Was it helpful?

Solution

Try change the last line to b[i].parentNode.removeChild(b[i].nextSibling); since with the current one you are removing the same element that you added in the previous step. Reason is that childNodes return live collection and when you add an element to the same parentNode your element @ b[i] is not the text node instead it will be the anchor that you just added. And also when dealing with the live collection cache the length before hand:

 var a = document.querySelectorAll('.post .content div');
 var b = a[0].childNodes;

 for(i=0, l=b.length;i<l;i++){ //Cache the length here in variable l
  var exp = /(\b(https?|ftp|file):\/\/[\-A-Z0-9+&@#\/%?=~_|!:,.;]*[\-A-Z0-9+&@#\/%=~_|])/ig;
   if(b[i].nodeType === 3){
      ...........
     b[i].parentNode.insertBefore(ahref,b[i]);
     b[i].parentNode.removeChild(b[i].nextSibling); //remove the next element to the added element
     //Or
     //b[i].parentNode.removeChild(b[i+1]);
    }
  }
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top