简体   繁体   中英

Accessing child elements in jquery

<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?

You have .filter()

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

DEMO

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/

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; }) 

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM