COp COp - 4 months ago 31
jQuery Question

JQUERY append data before sibling

I have got this html code

<div class="chatp">
<div class="chatpart">
</div>
</div>


And in my jquery i am trying to append

<div class='headchat'>

</div>


Inside
chatp
but it appends it after
chatpart
and here is what happens

<div class="chatp">
<div class="chatpart">

</div>

<div class='headchat'>

</div>
</div>


What i want is

<div class="chatp">
<div class='headchat'>

</div>
<div class="chatpart">

</div>
</div>

Answer

You can use prepend to append in start.

Insert content, specified by the parameter, to the beginning of each element in the set of matched elements.

Reference: https://api.jquery.com/prepend/

Example:

<div class="chatp">
            <div class="chatpart">
            </div>
    </div>

<script>
    $('.chatp').prepend('<div class="headchat"></div>'); 
</script>