如何使用 JavaScript 获取没有 HTML 元素的纯文本?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6743912/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to get the pure text without HTML element using JavaScript?
提问by John
I have the 1 button and some text in my HTML like the following:
我的 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>
When the user clicks the button, the content in the <p id='txt'>
will become the follow expected result:
当用户点击按钮时, 中的内容<p id='txt'>
会变成如下预期的结果:
<p id='txt'>
// All the HTML element within the <p> will be disappear
I am working in ABC company.
</p>
Can anyone help me how to write the JavaScript function?
谁能帮助我如何编写 JavaScript 函数?
Thank you.
谢谢你。
采纳答案by jcomeau_ictx
[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.
[2017-07-25] 由于这仍然是公认的答案,尽管这是一个非常hacky 的解决方案,但我将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>
回答by Gabi Purcaru
You can use this:
你可以使用这个:
var element = document.getElementById('txt');
var text = element.innerText || element.textContent;
element.innerHTML = text;
Depending on what you need, you can use either element.innerText
or element.textContent
. They differ in many ways. innerText
tries to approximate what would happen if you would select what you see (rendered html) and copy it to the clipboard, while textContent
sort of just strips the html tags and gives you what's left.
根据您的需要,您可以使用element.innerText
或element.textContent
。它们在很多方面都不同。innerText
如果您选择所看到的内容(呈现的 html)并将其复制到剪贴板,则尝试近似会发生什么,而textContent
只是剥离 html 标签并为您提供剩下的内容。
innerText
also has compatability with old IE browsers (came from there).
innerText
还兼容旧的 IE 浏览器(来自那里)。
回答by Sarath
If you can use jquery then its simple
如果你可以使用 jquery 那么它很简单
$("#txt").text()
回答by James
This answer will work to get just the text for any HTML element.
此答案将仅用于获取任何 HTML 元素的文本。
This first parameter "node" is the element to get the text from. The second parameter is optional and if true will add a space between the text within elements if no space would otherwise exist there.
第一个参数“节点”是从中获取文本的元素。第二个参数是可选的,如果 true 将在元素内的文本之间添加一个空格,否则那里不存在空格。
function getTextFromNode(node, addSpaces) {
var i, result, text, child;
result = '';
for (i = 0; i < node.childNodes.length; i++) {
child = node.childNodes[i];
text = null;
if (child.nodeType === 1) {
text = getTextFromNode(child, addSpaces);
} else if (child.nodeType === 3) {
text = child.nodeValue;
}
if (text) {
if (addSpaces && /\S$/.test(result) && /^\S/.test(text)) text = ' ' + text;
result += text;
}
}
return result;
}
回答by Matthias
Depending on what you need, you can use either element.innerText
or element.textContent
. They differ in many ways. innerText
tries to approximate what would happen if you would select what you see (rendered html) and copy it to the clipboard, while textContent
sort of just strips the html tags and gives you what's left.
根据您的需要,您可以使用element.innerText
或element.textContent
。它们在很多方面都不同。innerText
如果您选择所看到的内容(呈现的 html)并将其复制到剪贴板,则尝试近似会发生什么,而textContent
只是剥离 html 标签并为您提供剩下的内容。
innerText
is not just used for IE anymore, and it is supported in all major browsers. Of course, unlike textContent
, it has compatability with old IE browsers (since they came up with it).
innerText
不再仅用于 IE,所有主要浏览器都支持它。当然,与 不同的是textContent
,它与旧的 IE 浏览器兼容(因为他们想出了它)。
Complete example (from Gabi's answer):
完整示例(来自Gabi 的回答):
var element = document.getElementById('txt');
var text = element.innerText || element.textContent; // or element.textContent || element.innerText
element.innerHTML = text;
回答by Issac Gable
This works for me compiled based on what was said here with a more modern standard. This works best for multiple looks up.
这对我有用,根据此处所说的内容使用更现代的标准进行编译。这最适用于多次查找。
let element = document.querySelectorAll('.myClass')
element.forEach(item => {
console.log(item.innerHTML = item.innerText || item.textContent)
})
回答by Igor Dymov
That should work:
那应该工作:
function get_content(){
var p = document.getElementById("txt");
var spans = p.getElementsByTagName("span");
var text = '';
for (var i = 0; i < spans.length; i++){
text += spans[i].innerHTML;
}
p.innerHTML = text;
}
Try this fiddle: http://jsfiddle.net/7gnyc/2/
试试这个小提琴:http: //jsfiddle.net/7gnyc/2/
回答by Igor Dymov
function get_content(){
var returnInnerHTML = document.getElementById('A').innerHTML + document.getElementById('B').innerHTML + document.getElementById('A').innerHTML;
document.getElementById('txt').innerHTML = returnInnerHTML;
}
That should do it.
那应该这样做。
回答by Kamil Kie?czewski
Try (short version of Gabi answeridea)
尝试(加比答案想法的简短版本)
function get_content() {
txt.innerHTML = txt.textContent;
}
function get_content() {
txt.innerHTML = txt.textContent ;
}
span { background: #fbb}
<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>