In the sick, twisted word of cross-browser DOM-based JavaScript, sometimes you need to get the contents of an element. You usually use element.innerHTML, but often you don't want any existing sub-tags that might be in there. You want .innerText! But, innerText is only available on IE. Poop.
So, I needed this today, and my buddy Stuart found a solution here. Sick, yes. Twisted, yes. Works, yes. Moving on.
<script type="text/javascript"> var regExp = /<\/?[^>]+>/gi; function ReplaceTags(xStr){ xStr = xStr.replace(regExp,""); return xStr; } </script> All you need to do is pass it a string and it returns the string stripped of the tags. An example is shown below to grab the text from a div without the tags. <html> <head> <script type="text/javascript"> var regExp = /<\/?[^>]+>/gi; function ReplaceTags(xStr){ xStr = xStr.replace(regExp,""); return xStr; } </script> </head> <body> <div id="test"> <span id="span1">Test <u><b>Test</b></u> Test <br/><a href="#">Wow</a>!</span> </div> <script type="text/javascript"> var xContent = document.getElementById("test").innerHTML; var fixedContent = ReplaceTags(xContent); alert(fixedContent); </script> </body></html>[Eric's Weblog]
<script type="text/javascript"> var regExp = /<\/?[^>]+>/gi; function ReplaceTags(xStr){ xStr = xStr.replace(regExp,""); return xStr; } </script>
All you need to do is pass it a string and it returns the string stripped of the tags. An example is shown below to grab the text from a div without the tags.
<html> <head> <script type="text/javascript"> var regExp = /<\/?[^>]+>/gi; function ReplaceTags(xStr){ xStr = xStr.replace(regExp,""); return xStr; } </script> </head> <body> <div id="test"> <span id="span1">Test <u><b>Test</b></u> Test <br/><a href="#">Wow</a>!</span> </div> <script type="text/javascript"> var xContent = document.getElementById("test").innerHTML; var fixedContent = ReplaceTags(xContent); alert(fixedContent); </script> </body></html>[Eric's Weblog]
Scott at DevReach in Bulgaria in October
Developer Stand up Comedy - Coding 4 Fun
TechDays/DevDays Netherlands and Belgium:
Posts by Category Posts by Month
Greatest Hits Dev Tools List