I'm new to jQuery, familiar with PHP & CSS. I have nested, dynamically generated div's which I wish to send (the id's) to a server-side script to update numbers for. I want to check everything in the .content class. Only div's with id's should be sent for processing; however I'm having trouble making a recursive children() check...this is the best (non-recursively) I could do:
$(".content").children().each(function() {
if ($(this).attr('id').length == 0) {
$(this).children().each(function() {
if ($(this).attr('id').length == 0) {
$(this).children().each(function() {
if ($(this).attr('id').length == 0) {
$(this).children().each(function() {
alert($(this).attr('id'));
});
}
});
}
});
}
});
and it ju开发者_如何学JAVAst alert()'s the id's of everything at the level where they should be. There must be a better way to do this...thank you in advance for any advice. -Justin
Try:
var ids = $('.content div[id]').map(function() {
return this.id;
}).get();
.content div[id]
will select you all div descendants (at any level) of .content with non-empty ID attributes. The [id]
part is an example of the Has Attribute selector.
I have used .map
. to extract the IDs of the matches, and .get()
to convert the resulting object into a basic array.
Try it here: http://jsfiddle.net/M96yK/
You can do:
$(".content div[id]");
This will return a jQuery object that contains all div's which have id's specified
精彩评论