How to select ALL children (in any level) from a parent in jQuery?

JavascriptJqueryHtmlDom

Javascript Problem Overview


I have to .unbind() all elements from a parent node.

How can I select all children (at any level) from a parent?

Tried :

$('#google_translate_element *').unbind('click');

but it works only for the first children's level...

Here there is a test case

Javascript Solutions


Solution 1 - Javascript

Use jQuery.find() to find children more than one level deep.

> The .find() and .children() methods are similar, except that the > latter only travels a single level down the DOM tree.

$('#google_translate_element').find('*').unbind('click');

You need the '*' in find():

> Unlike in the rest of the tree traversal methods, the selector > expression is required in a call to .find(). If we need to retrieve > all of the descendant elements, we can pass in the universal selector > '*' to accomplish this.

Solution 2 - Javascript

I think you could do:

$('#google_translate_element').find('*').each(function(){
    $(this).unbind('click');
});

but it would cause a lot of overhead

Solution 3 - Javascript

It seems that the original test case is wrong.

I can confirm that the selector #my_parent_element * works with unbind().

Let's take the following html as an example:

<div id="#my_parent_element">
  <div class="div1">
    <div class="div2">hello</div>
    <div class="div3">my</div>
  </div>
  <div class="div4">name</div>
  <div class="div5">
    <div class="div6">is</div>
    <div class="div7">
      <div class="div8">marco</div>
      <div class="div9">(try and click on any word)!</div>
    </div>
  </div>
</div>
<button class="unbind">Now, click me and try again</button>

And the jquery bit:

$('.div1,.div2,.div3,.div4,.div5,.div6,.div7,.div8,.div9').click(function() {
  alert('hi!');
})
$('button.unbind').click(function() {
  $('#my_parent_element *').unbind('click');
})

You can try it here: http://jsfiddle.net/fLvwbazk/7/

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionmarkzzzView Question on Stackoverflow
Solution 1 - JavascriptKonerakView Answer on Stackoverflow
Solution 2 - JavascriptNicola PeluchettiView Answer on Stackoverflow
Solution 3 - JavascriptZoupView Answer on Stackoverflow