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

JavascriptHtml

Javascript Problem Overview


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>

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>

Can anyone help me how to write the JavaScript function?

Thank you.

Javascript Solutions


Solution 1 - Javascript

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.

innerText also has compatability with old IE browsers (came from there).

Solution 2 - Javascript

[2017-07-25] since this continues to be the accepted answer, despite being a very hacky solution, I'm incorporating https://stackoverflow.com/users/376873/gabi-purcaru">Gabi</a>'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>

Solution 3 - Javascript

If you can use jquery then its simple

$("#txt").text()

Solution 4 - Javascript

This answer will work to get just the text for any HTML element.

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.

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

Solution 5 - Javascript

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.

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

Complete example (from Gabi's answer):

var element = document.getElementById('txt');
var text = element.innerText || element.textContent; // or element.textContent || element.innerText
element.innerHTML = text;

Solution 6 - Javascript

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

Solution 7 - Javascript

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/

Solution 8 - Javascript

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.

Solution 9 - Javascript

Try (short version of Gabi answer idea)

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>

Solution 10 - Javascript

You want to change the I am working in ABC company. to 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.

element.innerHTML is a property that defines the HTML inside an element. If you type element.innerHTML = "<strong>This is bold</strong>, it'll make the text "This is bold" bold text.

element.textContent, on the other hand, sets the text in an element. 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

In your case, you can use either one. I'll use .textContent. The code to change the <p> element is below.

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." to something else.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionJohn View Question on Stackoverflow
Solution 1 - JavascriptGabi PurcaruView Answer on Stackoverflow
Solution 2 - Javascriptjcomeau_ictxView Answer on Stackoverflow
Solution 3 - JavascriptSarathView Answer on Stackoverflow
Solution 4 - JavascriptJamesView Answer on Stackoverflow
Solution 5 - JavascriptMatthiasView Answer on Stackoverflow
Solution 6 - JavascriptIssac GableView Answer on Stackoverflow
Solution 7 - JavascriptIgor DymovView Answer on Stackoverflow
Solution 8 - Javascriptuser827080View Answer on Stackoverflow
Solution 9 - JavascriptKamil KiełczewskiView Answer on Stackoverflow
Solution 10 - JavascriptSomeone AnonymousView Answer on Stackoverflow