MD66
MD66

Reputation: 101

'textContent' is null or not an object

i have a problem with this code this code run great on all browsers exept IE,my IE is 8.0 any solution? i won't using jquery sincerely Note: i changed Node.TEXT_NODE to 3 but other error occured:'textContent' is null or not an object

 <!DOCTYPE html>
 <html>
 <head>
 <script>

 function replaceText(oldText, newText, node){ 
   node = node || document.body; 

   var childs = node.childNodes, i = 0;

   while(node = childs[i]){ 
     if (node.nodeType == Node.TEXT_NODE){ 
  node.textContent = node.textContent.replace(oldText, newText); 
} else { 
  replaceText(oldText, newText, node); 
} 
     i++; 
   } 
 }

 </script>
 </head>
 <body>
 old
 <h1 id="myHeader" onclick="replaceText('old','new')">old Click me! whatever</h1>

 </body>
 </html>

i found it

   while(i < childs.length){
   if (rgx.test(document.body.innerHTML)){
   childs[i][textPropName] =childs[i][textPropName].replace(rgx,'new');
   }
   else
   {
   replaceText(oldText, newText,document.body.childNodes[i])
   }
        i++; 
      } 
    }  

Upvotes: 0

Views: 6023

Answers (2)

calorie712
calorie712

Reputation: 348

instead of textContent, use nodeValue

node.nodeValue = node.nodeValue.replace(oldText, newText); 

Upvotes: 2

Joseph Silber
Joseph Silber

Reputation: 220076

Node.TEXT_NODE & textContent are not available in IE8.


Use 3 instead of Node.TEXT_NODE, and use innerText if textContent is not available:

var textPropName = node.textContent === undefined ? 'innerText' : 'textContent';

if (node.nodeType == 3) {
    node[textPropName] = node[textPropName].replace(oldText, newText); 
} else { 
    replaceText(oldText, newText, node); 
}

You should probably cache that textPropName outside your function, so that you don't recheck it every single time the function is called (use document.body for the test).

Upvotes: 3

Related Questions