Fergoso
Fergoso

Reputation: 1582

Get all child elements by its parent

This is the div structure.

<div id="parentDiv">
  <input type="text" id="tf1">
  <input type="text" id="tf2">
  <input type="text" id="tf3">
  <button id="bt3">Text</button>
</div>

I use the below code by specifying individual IDs.

EDIT

There is a $(document).click set and I am avoiding a function being triggered if the user is currently typing anything into any of these text fields. All works okay. My question is instead of adding separate elements as the target is there a way to include all elements within the parent?

$(document).click(function(e) {
    if ($(e.target).closest("#tf1, #tf2, #tf3, #btn3").length) { //Can these  individual elements be replaced by using parent div ID?
      return;
    }

    if (typeof commonFunc == "function"){ 
        commonFunc();
    }  
});

By doing this I do not need to have track of new elements being added.

Upvotes: 0

Views: 124

Answers (2)

Jodi Supporter
Jodi Supporter

Reputation: 330

The solution is

if($(e.target).closest("#parentDiv").children().length)

Upvotes: 2

void
void

Reputation: 36703

$(e.target).children() // Will return all the children of whatever e.target is

EDIT

$(document).click(function(e) {
    if ($(e.target).children().length==0) {
      // No children element.
      return;
    }
    else{
      // There are some child elements.
    }
});

Upvotes: 0

Related Questions