Extracting Text from DOM Elements – the jQuery way
Ken Egozi has posted a nice sample for extracting all the text from all the children of a particular element. I’m not sure why does one needs such a function, but it is a very good practice in Javascript.
The trick is to check each of the element children’s nodeType and if it is TEXT_NODE (3), take it’s nodeValue.
As a huge fan of a jQuery library, I’ve decided to do this sample using jQuery. Here it is:
function extractFirstLevelTextFrom(elm) {
var text;
$(elm).children().each(function() { text += $(this).text(); });
return text;
}
This function can accept not only DOM elements, but any jQuery valid selector. However, in case the selector results numerous elements, only the first one will be handled. It is possible to handle every selected element by altering the code to something like that:
$(elm).each(function(){$(this).children()…. });
The .children() method of the jQuery object returns all the immediate children, end .each() method loops on every child. It is important to notice that the current context of the .each() method (this) is the DOM element, not the jQuery object, so we’re getting the jQuery object simply by selecting the DOM element. Also, .each() method accepts delegate as an argument. Here I’ve chosen to use the anonymous one.
The .text() method returns and empty string in case the element doesn’t have an innerText property, so there is no need to check the element type.