jQuery – How to get element text without child elements

The following jQuery script shows how to get the text from an element, without getting the text from any child elements.

For example, if you have a label that contains a span:

<label>Field label<span> * Required field</span></label>

If you just used .text() the returned value would be Field label * Required field

To just get Field label you need to use a combination of .clone(), .children(), .remove(), .end() and finally .text().

For example:

jQuery(this).heading.clone().children().remove().end().text();

Putting this together would look something like this …

jQuery(document).ready(function() {
jQuery("label").each(function(i) {
 var elementText = jQuery(this).clone().children().remove().end().text();
alert(elementText);
 });
});

Note: the code above assumes you are running WordPress, and therefore reference jQuery using ‘jQuery’ – if this is not the case replace jQuery with the dollar symbol – $

 

Reference: http://stackoverflow.com/questions/3442394/jquery-using-text-to-retrieve-only-text-not-nested-in-child-tags

Was this article helpful?

Related Articles