finding elements with text using jQuery

孤人 提交于 2019-12-05 04:58:25
$("#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.

You can make use of not and the empty selectors to get the non-empty elements while converting to an array can be achieved using get

$("#theDiv > :not(:empty)").get();

The above selector gets all the children elements of "theDiv" and that aren't empty (i.e. they either have children or text) and then converts the matched set to an array.

If you want only elements that have text inside them, this should work...

$("#theDiv > :not(:empty, :has(*))").get();

To get rid of elements that have whitespace you can make use of filter

$("#theDiv > :not(:has(*))").filter(function() { 
                 return $.trim(this.innerHTML).length > 0;
         }).get();

You could cycle through the children and grab everything that has a .text() value != ""

var array = [];
var divSelector = "div.mine";

$(divSelector).contents().each(function()
{
   // If not an element, go to next node.
   if (this.nodeType != 1) return true;       

   var element = $(this);
   if ($.trim(element.text()) != "")
     array.push(element);
});

array is the array of elements that have some text in them.

 $(function() {
        var array = new Array();
        $("#testDiv *").each(function(x, el) {

            if ($.trim($(el).text()) != '' ) {
                array.push(el);
            }
        });
        alert(array.length);
    });

d is the div under which you want to find things
v is an empty array
i you have to start out at 0.

The $.trim is used so that you don't get nodes that are just whitespace.

$("*",d).filter( function() { 
     return $.trim($(this).text()) != ""
  } ).each( function() { 
     v[i] = $(this).text(); 
     i++; 
  } );

One can also use v.push($(this))...which is something that totally slipped my mind.

Use the :contains selector:

var matches = new Array();
$('#start_point *:contains(' + text + ')').each(function(i, item) {
 matches.push( item );
}
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!