-1
<div id="main">
 <div id="1">
   <div>contents..</div>
   <div>contents..</div>
 </div>
 <div id="2">
   <div>contents..</div>
   <div>contents..</div>
 </div>
 <div id="3">
   <div>contents..</div>
   <div>contents..</div>
 </div>
</div>

How can i access all div object into a single array who have contents in there innerHTML?

EDIT

OK I tried this :

var totaldiv = $("#main").children();
var totalElements = [];
var c = 0;
$.each(totaldiv, function (i, v) {
    $(totaldiv[i]).children().each(function () {
        totalElements[c++] = $(this);
    });
});

Is there any more efficient way to do this?

Gaurav
  • 8,367
  • 14
  • 55
  • 90
  • 1
    **ANY** content or exactly the string **contents..** ?? And please... what `DIV` exactly, the parent DIV or the one that holds some text? – Roko C. Buljan Jun 01 '12 at 08:57

4 Answers4

3

You have .filter()

var divArr = $('#main div > div').filter(function() {
    return $(this).html();  // return those div not empty, has text or html element
});

DEMO

thecodeparadox
  • 86,271
  • 21
  • 138
  • 164
0

You'll probably want to exclude the higher level elements - if you use .text() on its own you'll get every element that contains text anywhere below it, not just in child nodes:

var haveContent = $('div').filter(function() {
    return $(this).children().length === 0 && $.trim($(this).text()) !== '';
}).get();

Demo at http://jsfiddle.net/alnitak/WNKLA/

Alnitak
  • 334,560
  • 70
  • 407
  • 495
0

At its most basic, the following will match your example above:

$('#main div div');

Assuming there are div elements who may not have any text content, you could try this:

$('#main div div').contents().filter(function(){ return this.length > 0; }) 
Phil.Wheeler
  • 16,748
  • 10
  • 99
  • 155
0

You can use .contents() to access all div contents in there innerhtml..

var arry = $('div:contains(contents)');

check this link;

http://api.jquery.com/contains-selector/

And

https://developer.mozilla.org/en/nodeType

And check this one.. It is similar to your question

Jquery: Checking to see if div contains text, then action

Community
  • 1
  • 1
stay_hungry
  • 1,448
  • 1
  • 14
  • 21