bdalina bdalina - 1 month ago 4
HTML Question

Append element inside an element on top of other elements inside

Is it possible to append an element right inside span element being on top of the parent span from other content?

html

<span id="parent">
<!-- I want the oldest placed here when something is click -->
<span id="child1">sample1</span>
<span id="child2">sample2</span>
<span id="child3">sample3</span>
<span>

<button id="write_IT">Put the older!</button>
<!--
//from php database

<span id="oldest">
Test
</span>
-->


jquery

$(document).ready(function() {
$(document).on('click', '#write_IT', function(e) {

var apb = $("#parent").after("<span id='parent'>");
apb.append('<span id="oldest">Test</span>');
});

});

Answer

Use prepend

$('#write_IT').on("click", function(){
  $("#parent").prepend('<span id="oldest">Test</span>');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<span id="parent">
    <!-- I want the oldest placed here when something is click -->
    <span id="child1">sample1</span>
    <span id="child2">sample2</span>
    <span id="child3">sample3</span>
<span> 

<button id="write_IT">Put the older!</button>

Comments