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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With