Zorgan
Zorgan

Reputation: 9173

How to select childs based on their position in the DOM tree

say I have html like this

<div class='parent'>
    <div class='dad'>
        <div class='teen'>
            <div class='baby'>
            </div>
        </div>
    </div>
    <div class='dad'>
    </div>
</div>

How do I target the divs based on how far they are from the parent? e.g. .baby has 3 parents ahead of it, and .teen has 2 parents ahead of it. Any way to do this? Because what I eventually wanna do is target every 2nd child(). So in this instance i'd like to select .dad and .baby. But I don't want to select a fixed amount, I want it to infinitely select every 2nd child() in the DOM tree.

Upvotes: 3

Views: 134

Answers (5)

night11
night11

Reputation: 58

This one is using jquery :odd selector.

$("div:odd").css("background-color", "yellow");
$("div:even").css("background-color", "green");

Here the alternate div's are colored differently.

Upvotes: 1

John Ambrose
John Ambrose

Reputation: 187

you can do it like this for single div-

 $('.dad').children().children().eq(0);

and if you have more than one div and u need for all you can try this-

$('div').each(function(){
$(this).children().children().eq(0);
})

Upvotes: 0

ibrahim mahrir
ibrahim mahrir

Reputation: 31712

var $result = $("div").filter(function() {
  return $(this).parents("div").length % 2 != 0; // if the number of div parents is not a pair number
});

$result.each(function() {
  $(this).css("background", "red");
});
div {
  border: 1px solid black;
  background: white;
  padding: 10px;
  margin: 10px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
  <div>
    <div>
      <div>
      </div>
      <div>
        <div>
        </div>
      </div>
    </div>
  </div>
  <div>
  </div>
</div>

Note: If you want to include all parents then use this:

return $(this).parents().length % 2 != 0;

Upvotes: 4

RRajani
RRajani

Reputation: 409

function nthLevelChield(n){
    var targetedNode=$('.parent');
    for(var i=0; i<n ; i++){
         targetedNode=targetedNode.children().eq(0);
       }
    return targetedNode;
}

Where n is child level variable.

Upvotes: 0

Vivek Pradhan
Vivek Pradhan

Reputation: 4857

I think nth child selector should do the trick.

Relevant documentation

Example:

$("p:nth-child(3)")

The above code snippet would select each <p> element that is the third child of its parent. You can get fancy with the selectors and values. Further reference on CSS selectors.

Upvotes: 0

Related Questions