Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the text of a div which is not a part of any other container in JQuery?

This should be real easy. Given below is the HTML.

<div id='attachmentContainer'>
    #Attachment#
    <span id='spnAttachmentName' class='hidden'>#AttachmentName#</span>
    <span id='spnAttachmentPath' class='hidden'>#AttachmentPath#</span>
</div>  

I want to get just the #Attachment# and not the other text. When I tried

$("#attachmentContainer").text() 

it gives out all #Attachment#, #AttachmentName# as well as #AttachmentPath#. I know I could just put #Attachment# into another span and access it directly but I was just intrigued on how to do this. Any help is much appreciated.

like image 942
Raja Avatar asked May 05 '10 18:05

Raja


1 Answers

Since your text happens to be the first child node of the <div>:

var firstChild = $("#attachmentContainer")[0].firstChild;
var textValue  = firstChild.nodeType == 3 ? $.trim(firstChild.nodeValue) : "";

The nodeType check is meant to be a safeguard - it makes sure you are actually handling a text node - the firstChild might be something different after all. React accordingly, this is just an example.

To retrieve the value of all text children (or a specific one), just loop over the childNodes collection of your element, concatenating all bits you find into a string:

// the optional "at" parameter lets you define which text node you want
// if not given, this returns all text nodes concatenated
$.fn.ownText = function(at) { 
  var result = [], node = this[0];
  if (!(node && node.childNodes)) return;
  for (var i=0; i<node.childNodes.length; i++) {
    var child = node.childNodes[i];
    if (child.nodeType != 3) continue;
    var t = $.trim(child.nodeValue);
    if (t != '') result.push(t);
  }
  return at ? result[at-1] : result.join(' ');
}

var text = $("#attachmentContainer").ownText();  // all text children
var text = $("#attachmentContainer").ownText(1); // first text child only
like image 61
Tomalak Avatar answered Sep 21 '22 19:09

Tomalak