简体   繁体   English

如何使用JavaScript获取没有HTML元素的纯文本?

[英]How to get the pure text without HTML element using JavaScript?

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 function?

Thank you.谢谢你。

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 .根据您的需要,您可以使用element.innerTextelement.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. innerText试图估计如果您将 select 您看到的内容(呈现的 html)并将其复制到剪贴板会发生什么,而textContent只是剥离 html 标签并为您提供剩下的内容。

innerText also has compatability with old IE browsers (came from there). innerText还与旧的 IE 浏览器兼容(来自那里)。

[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] 因为这仍然是公认的答案,尽管这是一个非常老套的解决方案,但我将Gabi的代码合并到其中,留下我自己的作为一个坏例子。

 // 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>

If you can use jquery then its simple如果你可以使用 jquery 那么它很简单

$("#txt").text()

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.第一个参数“node”是从中获取文本的元素。 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;
}

Depending on what you need, you can use either element.innerText or element.textContent .根据您的需要,您可以使用element.innerTextelement.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. innerText试图估计如果您将 select 您看到的内容(呈现的 html)并将其复制到剪贴板会发生什么,而textContent只是剥离 html 标签并为您提供剩下的内容。

innerText is not just used for IE anymore , and it is supported in all major browsers . innerText不再仅仅用于 IE ,它在所有主流浏览器中都得到了支持 Of course, unlike textContent , it has compatability with old IE browsers (since they came up with it).当然,与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;

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)
  })

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/

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.那应该这样做。

Try (short version of Gabi answer idea)尝试(Gabi回答想法的简短版本)

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>

You want to change the I am working in ABC company.你想改变I am working in ABC company. to I am working in ABC company. I am working in ABC company. . . These are the same strings, so I don't see a reason to, but you can accomplish this by using the JavaScript innerHTML or textContent .这些是相同的字符串,所以我没有理由这样做,但您可以通过使用 JavaScript innerHTMLtextContent来完成此操作。

element.innerHTML is a property that defines the HTML inside an element. element.innerHTML是一个在元素内定义 HTML 的属性。 If you type element.innerHTML = "<strong>This is bold</strong> , it'll make the text "This is bold" bold text.如果您输入element.innerHTML = "<strong>This is bold</strong> ,它将使文本“This is bold”变为粗体文本。

element.textContent , on the other hand, sets the text in an element.另一方面, element.textContent设置元素中的文本。 If you use element.textContent = "<strong>This is bold</strong> , The text "This is bold" will not be bold. The user will literally see the text " This is bold如果你使用element.textContent = "<strong>This is bold</strong> ,文本 "This is bold" 不会是粗体的。用户会从字面上看到文本 " This is bold

In your case, you can use either one.在您的情况下,您可以使用其中任何一种。 I'll use .textContent .我将使用.textContent The code to change the <p> element is below.更改<p>元素的代码如下。

function get_content(){
   document.getElementById("txt").textContent = "I am working in ABC company.";
}

<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>

This, unfortunately, will not change it because it'll change it to the same exact text.不幸的是,这不会更改它,因为它会将其更改为完全相同的文本。 You can chance that by changing the string "I am working in ABC company."您可以通过更改字符串“我在 ABC 公司工作”来实现这一点。 to something else.到别的东西。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM