So really you want significant text (ie other than whitespace, because in your second example there's probably tabs and returns between the span
start tag and the b
) of #size
, or, if that doesn't exist, the significant text of its first element:
// Is text just whitespace?
function isWhitespace(text){
return text.replace(/\s+/,'').length === 0;
}
// Get the immediate text (ie not that of children) of element
function getImmediateText(element){
var text = '';
// Text and elements are all DOM nodes. We can grab the lot of immediate descendants and cycle through them.
for(var i = 0, l = element.childNodes.length, node; i < l, node = element.childNodes[i]; ++i){
// nodeType 3 is text
if(node.nodeType === 3){
text += node.nodeValue;
}
}
return text;
}
function getFirstTextNode(element){
var text = getImmediateText(element);
// If the text is empty, and there are children, try to get the first child's text (recursively)
if(isWhitespace(text) && element.children.length){
return getFirstTextNode(element.children[0])
}
// ...But if we've got no children at all, then we'll just return whatever we have.
else {
return text;
}
}