Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

finding elements with text using jQuery

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!

like image 391
Tim Sheiner Avatar asked Jun 19 '09 16:06

Tim Sheiner


2 Answers

$("#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 :)

like image 166
Vincent Robert Avatar answered Nov 16 '22 02:11

Vincent Robert


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.

like image 25
TM. Avatar answered Nov 16 '22 03:11

TM.