roberto tomás
roberto tomás

Reputation: 4687

How to find all elements with inner text in jQuery

What is the jquery to find all elements that contain inner text?

$("*:contains(*)") just seems wrong...

Upvotes: 0

Views: 141

Answers (3)

Jimmie Johansson
Jimmie Johansson

Reputation: 1962

What is "inner text"? Is it something like this you want to do?

var elems = [];
$('*').each(function(){
    if ($(this).text().length > 0) {
        elems.push($(this));
    }
});

console.log('Elements with text: ' + elems.length);
console.log('All elements with text:' + elems);

Upvotes: 1

Jason P
Jason P

Reputation: 27012

If having "inner text" is defined as having a text node, I think this will do what you want:

http://jsfiddle.net/TMyRr/

var $elementsWithTextNodes = $('*').filter(function(){
    return $(this).contents().filter(function() {
       return this.nodeType == 3 && $.trim($(this).text()) != ''; 
    }).length;
});

Upvotes: 0

BenR
BenR

Reputation: 2936

$.filter("*") will do what you're looking for.

Example using innerHTML:

$(document.getElementById("elementID").innerHTML).filter("*");

Upvotes: 1

Related Questions