本文介绍了如何使用JavaScript获得没有HTML元素的纯文本?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有1按钮和HTML中的一些文本,如下所示:
I have the 1 button and some text in my HTML like the following:
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'>
中的内容将成为以下预期结果:
When the user clicks the button, the content in the <p id='txt'>
will become the follow expected result:
<p id='txt'>
// All the HTML element within the <p> will be disappear
I am working in ABC company.
</p>
有人可以帮我编写JavaScript函数吗?
Can anyone help me how to write the JavaScript function?
谢谢.
推荐答案
[2017-07-25]因为尽管这是一个非常棘手的解决方案,但它仍然是公认的答案,因此我将的代码添加到其中,我自己留下的代码就是一个不好的例子.
[2017-07-25] since this continues to be the accepted answer, despite being a very hacky solution, I'm incorporating Gabi's code into it, leaving my own to serve as a bad example.
// 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;
}
.A {
background: blue;
}
.B {
font-style: italic;
}
.C {
font-weight: bold;
}
<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>
这篇关于如何使用JavaScript获得没有HTML元素的纯文本?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!