How do I get the value of a text node?

L

laredotornado

Hi,

If I have a TD, whose id = "myTd," that only contains text within
it,how do extract that text?

Thanks, - Dave
 
L

Lasse Reichstein Nielsen

laredotornado said:
If I have a TD, whose id = "myTd," that only contains text within
it,how do extract that text?

Find all child nodes that are text nodes, and extract their content.
Even if the td only contains text, that text might be split over
more than one text node (worst case).

var td = document.getElementById("myTd");
var textNodeContents = [];
for(var chld = td.firstChild; chld; chld = chld.nextSibling) {
if (chld.nodeType == 3) { // text node
textNodeContents.push(chld.nodeValue);
}
}
var text = textNodeContents.join("");


/L
 
L

laredotornado

laredotornado said:
If I have a TD, whose id = "myTd," that only contains text within
it,how do extract that text?

Find all child nodes that are text nodes, and extract their content.
Even if the td only contains text, that text might be split over
more than one text node (worst case).

var td = document.getElementById("myTd");
var textNodeContents = [];
for(var chld = td.firstChild; chld; chld = chld.nextSibling) {
  if (chld.nodeType == 3) { // text node
    textNodeContents.push(chld.nodeValue);
  }}

var text = textNodeContents.join("");

/L

I'm noticing some odd behavior. When I call

var ele = document.getElementById(id);
var innerHtml = ele.innerHTML;
var text = ele.nodeValue;

The value of "innerHtml" yields a value whereas the value of "text"
comes up empty. The object type of ele is [object
HTMLTableCellElement].

Any other insights are greatly appreciatd, - Dave
 
J

Joost Diepenmaat

laredotornado said:
I'm noticing some odd behavior. When I call

var ele = document.getElementById(id);
var innerHtml = ele.innerHTML;
var text = ele.nodeValue;

The value of "innerHtml" yields a value whereas the value of "text"
comes up empty. The object type of ele is [object
HTMLTableCellElement].

That's because table cells, and in fact most HTML node types, do not
have a useful nodeValue property. HTML text is part of the value of
Text nodes, which are children of the cell (if there is any text).

IOW, any characters "in between" tags and some other special
constructs results in one or more Text nodes containing the character
data.
Any other insights are greatly appreciatd, - Dave

See http://developer.mozilla.org/en/docs/DOM:element.nodeValue
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
474,142
Messages
2,570,818
Members
47,362
Latest member
eitamoro

Latest Threads

Top