On May 30, 5:48 am, DaveG <[EMAIL PROTECTED]> wrote:
> How do I find the first text-node of a given DOM object?
>
> Input: <div><p>here is</p> some text</div>
> Output: " some text"
>
> Input: <h1><a href="#id1"></a>Header 1</h1>
> Output: "Header 1"

I'm not sure what you are really after.  If you are after the text
content of an element, then something like the following will do the
trick:

 function getText(el) {
   if (typeof el.textContent == 'string') return el.textContent;
   if (typeof el.innerHTML == 'string') return el.innerHTML;
 }

However, if you really are after the first text node that is child of
the element, loop over the child nodes:

 function getFirstTextNode(el) {
   var kids = el.childNodes;
   for (var i=0, len=kids.length; i<len; i++){
     if (kids[i].nodeType == 3) return kids[i];
   }
 }


If you are after the first text descendent of a node, use recursion:

 function getFirstTextNode(el) {
   var kids = el.childNodes;
   var n;
   for (var i=0, len=kids.length; i<len; i++){
     n = kids[i];
     if ( n.nodeType == 3) return n;
     n = getFirstTextNode(n);
     if (n && n.nodeType && n.nodeType == 3) return n;
   }
 }


--
Rob

Reply via email to