How to get the pure text without HTML element using 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).
[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>
If you can use jquery then its simple
$("#txt").text()
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;
}