Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Recursively disabling all children of an element

Tags:

jquery

This might be a yes/no type of question.

I'm trying to disable absolutely all children of an element in jquery.

Does calling

$('#id_of_an_element').children().do(function(){
    do_something;
});

recursively call all children of an element, or does it just do_something to all the direct descendants of an_element?

Help is appreciated,

Josh

like image 372
lowerkey Avatar asked Jan 29 '11 17:01

lowerkey


3 Answers

Given a jQuery object that represents a set of DOM elements, the .children() method allows us to search through the immediate children of these elements in the DOM tree and construct a new jQuery object from the matching elements. The .find() and .children() methods are similar, except that the latter only travels a single level down the DOM tree. Note also that like most jQuery methods, .children() does not return text nodes; to get all children including text and comment nodes, use .contents().

http://api.jquery.com/children/

You can do this if you want to act on all descendants at any level of nesting:

$('#id_of_an_element').find('*').attr('disabled', true);

or using the descendant selector:

$('#id_of_an_element *').attr('disabled', true);
like image 67
karim79 Avatar answered Nov 13 '22 05:11

karim79


Since you want to affect all descendants, just do this:

$('#id_of_an_element *').each(function() {
    // do something
});

But I'd be curious to know what exactly you're doing.

The disabled property is meaningless for many element types. It could be that whatever you're doing will benefit from the inheritance of CSS.

Or if you actually want the disabled property, then you might as well just target form elements.

$('#id_of_an_element :input').attr('disabled','disabled');
like image 8
user113716 Avatar answered Nov 13 '22 05:11

user113716


You can do

function disableChildren(obj) {
    obj.children().each(function(i, val) {
         disable(val);
         disableChildren(val);
    });
}

disableChildren($("#id"));

See .each There doesn't appear to be a .do method.

You'll have to implement disable as a function to do what every you want when you say "disable"

like image 3
Raynos Avatar answered Nov 13 '22 05:11

Raynos