简体   繁体   中英

Javascript textContent returns undefined

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?

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 &amp; bye</strong>';
alert(elem.textContent || elem.innerText || ''); // displays "hi & bte"

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.

Edit

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

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);​

Live test case .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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