This is my code:
var text1 = "↵,<strong>bla bla</strong>";//here text1 has value
text1 = text1.textContent;//here it is undefined
Why? And how to resolve it?
You can use jQuery for such task.
First add reference to jQuery library, then it's as simple as this:
var text1 = "↵,<strong>bla bla</strong>";//here text1 has value
text1 = $("<div>").html(text1).text();
alert(text1);
textContent
(too used to IE only innerText) are you sure this covers all cases including complicated HTML structures - Shadow Wizard 2012-04-04 09:48
.text()
ThiefMaster 2012-04-04 09:57
text1
is a plain string, not a DOM element.
As you can see in MDN, textContent
is a property of Node
objects. String
objects on the contrary do not have such a property.
And since removing tags is a pretty simple task where it does not make sense to add a rather big library (even though jQuery is great as soon as you want to do more stuff with the DOM), here's a simple way to do it:
var elem = document.createElement('div');
elem.innerHTML = '<strong>hi & bye</strong>';
alert(elem.textContent || elem.innerText || ''); // displays "hi & bte"
elem.innerText || elem.textContent
should work though - Shadow Wizard 2012-04-04 09:46
alert(elem.textContent || elem.innerText || '');
RobG 2012-04-05 04:36
text1
is a string, not a DOM node.
You would need to turn the HTML into a DOM (either by adding it to a document with innerHTML
or by writing/finding a JS DOM parser) before you can use DOM methods on it.
Others have given you the answer, I'll just comment.
While textContent has been around since DOM 3 Core (about 8 years) most browsers have implemented the (MS proprietary) innerText property. So if you have a node, you can do:
var theTextContent = typeof node.textContent == 'string'? node.textContent : node.innerText;
or write a more robust function.
here's a full solution:
function getText(el) {
return el.textContent || el.innerText || '';
}
var text1 = "<strong>bla bla</strong>"
var d = document.createElement('div');
d.innerHTML = text1;
alert(getText(d)); // bla bla