I want to create an array of all the html elements within a div that contain text strings, such as
<p>some string</p>.
I don't want to get hold of the strings, I want the array items to be the elements (in the example, would be the p node). I do not know before hand what the strings will be, so I can't look for string values to match. I also don't want empty text nodes to end up in the array.
Thanks!
$("#my_div *").filter(function()
{
var $this = $(this);
return $this.children().length == 0 && $.trim($this.text()).length > 0;
})
This version will not return parent elements that contains the elements having texts, only the last level elements.
May not be the fastest but works quite well on StackOverflow homepage :)
A custom selector could be helpful in your case:
jQuery.expr[':'].hasText = function(element, index) {
// if there is only one child, and it is a text node
if (element.childNodes.length == 1 && element.firstChild.nodeType == 3) {
return jQuery.trim(element.innerHTML).length > 0;
}
return false;
};
After that, you can simply do this:
$('#someDiv :hasText') // will contain all elements with text nodes (jQuery object)
$('#someDiv :hasText').get() // will return a regular array of plain DOM objects
I am assuming that you are only trying to select elements that have ONLY text inside of them.
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