小编典典

通过JavaScript获取没有HTML元素的纯文本?

javascript

我的HTML中有1个按钮和一些文本,如下所示:

function get_content(){
   // I don't know how to do in here!!!
}

<input type="button" onclick="get_content()" value="Get Content"/>
<p id='txt'>
<span class="A">I am</span>
<span class="B">working in </span>
<span class="C">ABC company.</span>
</p>

当用户单击按钮时,中的内容<p id='txt'>将成为以下预期结果:

<p id='txt'>
// All the HTML element within the <p> will be disappear
I am working in ABC company.
</p>

谁能帮我如何编写javascript函数?谢谢。


阅读 345

收藏
2020-05-01

共1个答案

小编典典

尽管这是一个非常棘手的解决方案,但由于它仍然是公认的答案,因此我将Gabi的代码合并到其中,而我自己的代码将成为一个不好的例子。

<style>
.A {background: blue;}
.B {font-style: italic;}
.C {font-weight: bold;}
</style>

<script>
// my hacky approach:
function get_content() {
     var html = document.getElementById("txt").innerHTML;
     document.getElementById("txt").innerHTML = html.replace(/<[^>]*>/g, "");
}
// Gabi's elegant approach, but eliminating one unnecessary line of code:
function gabi_content() {
    var element = document.getElementById('txt');
    element.innerHTML = element.innerText || element.textContent;
}
// and exploiting the fact that IDs pollute the window namespace:
function txt_content() {
    txt.innerHTML = txt.innerText || txt.textContent;
}
</script>

<input type="button" onclick="get_content()" value="Get Content (bad)"/>
<input type="button" onclick="gabi_content()" value="Get Content (good)"/>
<input type="button" onclick="txt_content()" value="Get Content (shortest)"/>
<p id='txt'>
<span class="A">I am</span>
<span class="B">working in </span>
<span class="C">ABC company.</span>
</p>
2020-05-01