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.
在基于DOM的跨浏览器JavaScript中,有时您需要获取元素的内容。 您通常使用element.innerHTML,但通常您不希望在其中存在任何现有的子标记。 您想要.innerText! 但是,innerText仅在IE上可用。 船尾。
So, I needed this today, and my buddy Stuart found a solution here. Sick, yes. Twisted, yes. Works, yes. Moving on.
因此,我今天需要这个,而我的好友Stuart在这里找到了解决方案。 病了,是的。 扭曲,是的。 可以,是的。 继续。
<script type="text/javascript">
var regExp = /<\/?[^>]+>/gi;
function ReplaceTags(xStr){
xStr = xStr.replace(regExp,"");
return xStr;
}
</script><script type =“ text / javascript”> var regExp = / <\ /?[^>] +> / gi; 函数ReplaceTags(xStr){ xStr = xStr.replace(regExp,“”); 返回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.
您需要做的就是将一个字符串传递给它,然后返回去除了标签的字符串。 下面显示了一个示例,该示例从没有标签的div抓取文本。
<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]<html> <头> <script type =“ text / javascript”> var regExp = / <\ /?[^>] +> / gi; 函数ReplaceTags(xStr){ xStr = xStr.replace(regExp,“”); 返回xStr; } </ script> </ head> <身体> <div id =“ test”> <span id =“ span1”>测试<u> <b>测试</ b> </ u>测试<br/> <a href="#">哇</a>!</ span> </ div> <script type =“ text / javascript”> var xContent = document.getElementById(“ test”)。innerHTML; var fixedContent = ReplaceTags(xContent); alert(fixedContent); </ script> </ body> </ html> [ Eric的博客]