Alok
Alok

Reputation: 522

Keep a div as last child of its parent even after any new div is appended to its parent

Hello i am quite struggling with a problem. The structure is like :-

<div class="parent" >
    <div class="child1" >
    </div>
    <div class="childToBeKeptLast" >
    </div>
</div>

After insertion of new child

<div class="parent" >
      <div class="child1" >
    </div>
     <div class="child2" >
    </div>
    <div class="childToBeKeptLast" >
    </div>
</div>

Thus I always want to keep my child with class "childToBeKeptLast" as last child no matter how many insertion take place in the parent div.How to achieve this by css or jquery ??

Any help will be appreciated ... Thank you ...

Upvotes: 0

Views: 2064

Answers (3)

G-Cyrillus
G-Cyrillus

Reputation: 106068

For Info, in CSS with young browser, the flex model can help you to keep one last .. seen at screen:DEMO

BASIC CSS needed :

.parent {
  display:flex;
  flex-direction:column;
}
.childToBeKeptLast {
  order:1;
}
/* for demo, make some content*/
div:before {
  content:attr(class);
}

The :not() selector works too if you want somehow filter some browsers

:not(.childToBeKeptLast) {
  order:-1;/* puts anything that has not this class up in front */
}

HTML of demo:

<div class="parent" >
    <div class="child1" >
    </div>
    <div class="childToBeKeptLast" >
    </div>
      <div class="child1" >
    </div>
      <div class="whatever clss wich is not meant to be last seen" >
    </div>
      <div class="child1" >
    </div>
      <div class="child1" >
    </div>
</div>

Upvotes: 2

h3li0s
h3li0s

Reputation: 633

You also use:

$('.childToBeKeptLast').before('<div class="child2"></div>');

Upvotes: 0

Rajaprabhu Aravindasamy
Rajaprabhu Aravindasamy

Reputation: 67217

Try to use .insertBefore() at this context,

$('.child2').insertBefore('.parent .childToBeKeptLast');

So the above code would insert the new children before of the element which is having the class childToBeKeptLast and which is the descendant of the element with the class parent

Upvotes: 5

Related Questions