Talha Ahmed Khan
Talha Ahmed Khan

Reputation: 15433

JQuery: Use appendTo() and before() at same time

I have a situation that I have a to insert a div.msg in a div.chat-msgs.

<div class="chat-msgs">
  <div class="msg me">How are u?</div>
  <div class="msg">Good, Thanks..</div>
</div>

It would be a simple to use $('div.msg').appendTo($('div.chat-msgs')).

The problem occurs that some time I have some other divs regarding events like

<div class="chat-msgs">
  <div class="msg me">How are u?</div>
  <div class="msg">Good, Thanks..</div>
  <div class="event">XYZ is typing a message</div>
</div>

All I want that if any message enter into div.chat-msgs it would be at the bottom but above the div.event.

<div class="chat-msgs">
  <div class="msg me">How are u?</div>
  <div class="msg">Good, Thanks..</div>
  <div class="msg">This is a new message</div>
  <div class="event">XYZ is typing a message</div>
</div>

So I was wondering if its possible that we can use .appendTo() and .before() at the same time.

Upvotes: 0

Views: 465

Answers (2)

Mihai Matei
Mihai Matei

Reputation: 24276

you can use insertBefore() method which is documented here

Upvotes: 1

elclanrs
elclanrs

Reputation: 94101

You could just test if event exists:

if ($('div.chat-msg').find('.event').length) {
  // exists, use before
} else {
  // doesn't exist, use append
}

Upvotes: 2

Related Questions