Norris
Norris

Reputation: 2238

jQuery insert after the last element

I want to add elements after the last one. My current code

<div class="find"><div id="FirstElement"> /*First element loaded first */ </div><div>

$('#AddNextElement' + id).click(function (e) {
   $('<div id="NextElement' + id +'">' + /*Add after the last element*/ + '</div>').insertAfter($("#FirstElement"));
}

Current it adds only it after the first element:

1 4 3 2

I want it to add after the last element every time:

1 2 3 4

I've followed these links and I didn't find what I'm looking for:

jQuery insertAfter last item

insertAfter specific element based on ID

jQuery: Add element after another element

Thank you in advance!.

How I fixed it:

$('#AddNextElement' + id).click(function (e) {
   $('<div id="NextElement"' + id +'>' + /*Add after the last element*/ + '</div>').insertAfter($("#FirstElement").parent().find('.Finder').last());
}

I found the .parent().find('.find').last(); then insert after the last

Upvotes: 18

Views: 65443

Answers (8)

Oussama Khoubrane
Oussama Khoubrane

Reputation: 9

You can just use this:

jQuery('##AddNextElement').last().after();

Upvotes: 0

Omar bakhsh
Omar bakhsh

Reputation: 1054

**hope this will make you understand well GitHub:Omar-baksh **

// code by GitHub: omar-baksh 
// jquery is required online !!


							/*
							//this scricp test if jquery loded 

							window.onload = function() {
 							   if (window.jQuery) {  
 							       // jQuery is loaded  
 							       alert("Yeah!");
 							   } else {
 							       // jQuery is not loaded
 							       alert("Doesn't Work");
 							   }
							}
							*/

var gfather = document.getElementsByClassName('Gfather');
var father =  document.getElementsByClassName('father');
var son = document.getElementsByClassName('son');


function gf(argument) {
$(gfather).mouseenter(function(){
	for (let i = 0; i < father.length; i++) {
		father[i].style.display='block';
	};
// show father fun() body show  body last ...

});

$(father).mouseenter(function(){
	for (let i = 0; i < son.length; i++) {
		son[i].style.display='block';
	};
// son show  body last ...
});



	// gf body last ...
}

// show form setting bottun fun()

function add(){
	 const x = document.getElementById("frm").style.display='block';
	alert('setting opened');
	
}

// form  add element fun()
var clslist=document.getElementsByClassName("list");
var inher =document.getElementById("level");
var num =document.getElementById("num").value;
var txt =document.getElementById("inp-text");
// var add-btn = document.getElementById("btn-secsuce");

/*
$("#inher").change(function () {
	alert(inher);
	document.getElementById("inp-text")="you selected"+ document.getElementById("level").value;
	// body...
});
*/
var clss ="";
var ii;
$( "#btn-secsuce" ).click(function () {    
//txt.value="class name "+inher.value;  
    if( String(inher.value) =="Grand father"){
      clss ="Gfather";
 jQuery('<div/>', {
    id: Math.ceil(Math.random() * 999),
    text:txt.value,
    "class": clss,
    title: clss+clss.length
}).appendTo(clslist);

	alert("add class "+inher.value+gfather.length);
}


else { // alert("class enhhert is roung you chose " +inher.value )
	
}


/// add father to g father

if( String(inher.value) =="father"){
 var txt2 = $("<div class="+"father"+"></div>").text(txt.value);
  $(father[num-1]).after(txt2);


}

else{
	


}


});  
.Gfather{
	 width: 60px;
	 height: auto;
border-left: 6px dashed  red;
border-bottom: 6px dashed  red;
  background-color: silver;
 top:0;
  display:block;
position:relative ;
margin-left:9px;
 white-space: nowrap;
}

.father{
	 width: 60px;
    border-left: 6px dashed  red;
border-bottom: 6px dashed  red;
 bottom:0;
  padding-top:0px;
border-right-width: small;
left:66px;
   white-space: nowrap;
position:relative ;
background-color: #550088;
color:white;
display: block;
}
<head>
  <title>tree js</title>
  <meta charset="utf-8">
  <link rel="stylesheet" type="text/css" href="./tree.css">
</head>
<body>
<div class="list">
      <div class ="Gfather" onmouseover="gf();">
      grand father 1
      
      </div> 
         <div class ="father">
          father
               
          </div>
        
        

            <div class ="son">son
           </div>
    <div class ="son">son
           </div>
   
       
          </div>
          <!-- add element show setting btn -->

          <button id="add" onclick="add()" > add setting</button>

       <form id="frm">

                                                     <h6>1</h6>
           <select id="level">
               <option>Grand father</option>
               <option>father</option>
               <option>son</option>
               
           </select>

          
                                                      <h6>2</h6> 
           <select id="num">
               <option>1</option>
               <option>2</option>
               <option>3</option>
               <option>4</option>
               <option>5</option>
               <option>6</option>
               <option>7</option>
               <option>8</option>
               <option>9</option>
           </select>
           <br>
                                                       <h6>3</h6>
            <input id="inp-text" type="text">

                                                 <h5 >4</h5>
            <button type="button" id="btn-secsuce"  >Add The Element  </button>
       </form>
       <script
  src="https://code.jquery.com/jquery-3.4.1.js"
  integrity="sha256-WpOohJOqMqqyKL9FccASB9O0KwACQJpFTUBLTYOVvVU="
  crossorigin="anonymous"></script>
       <script type="text/javascript" src="./tree.js"></script>

Upvotes: 0

Ashish Panchal
Ashish Panchal

Reputation: 504

You can try below code, it will add the new div after the last "NextElement" div

JS Code:

$(function(){
    $('#AddNextElementButton').on("click", function (e) {
        var id = $("[id^='NextElement']").length ? $("[id^='NextElement']").length+1 : 1;

        if($("[id^='NextElement']").length){
            $('<div id="NextElement'+ id +'">Add after the last element</div>').insertAfter($('[id^="NextElement"]').last());
        } else {
            $('<div id="NextElement'+ id +'">Add after the last element</div>').insertAfter($('#FirstElement'));
        }
    });
});

Upvotes: 0

Frogmouth
Frogmouth

Reputation: 1818

HTML:

<div id="FirstElement"> First element loaded first  </div>

<div id="AddNextElement">Click me</div>

JS:

var current = 0;
$('#AddNextElement').click(function (e) {
    var $el = (current == 0) ? $("#FirstElement") : $("#NextElement"+current);
    current++;
    $('<div id="NextElement' + current +'">Other element '+current+'</div>').insertAfter($el);
});

Try yourself on jsfiddle

Upvotes: 1

Smallcampus Tin
Smallcampus Tin

Reputation: 1

one way is to store the last element.

<div id="FirstElement"> /*First element loaded first */ </div>

var lastElement = $('#FirstElement');

$('#AddNextElement' + id).click(function (e) {
    var element = $('<div id="NextElement"' + id +'>' + /*Add after the last element*/ + '</div>'));
    element.insertAfter(lastElement);
    lastElement = element;
}

Upvotes: 0

Thanasis Pap
Thanasis Pap

Reputation: 2051

How about adding a class to all elements? It will be easier to find the last:

$('.element-class:last').after('<div class="element-class" id="NextElement"' + id +'>' + /*Add after the last element*/ + '</div>');

This of course means that your First element must also have the class:

<div class="element-class" id="FirstElement"> /*First element loaded first */ </div>

Upvotes: 9

Pat Dobson
Pat Dobson

Reputation: 3299

Find the last element in the DOM, in your case it'll be 'NextElementxx' and then use 'after':

$('#NextElement2').after( ..new stuff.. );

Upvotes: 1

Bhojendra Rauniyar
Bhojendra Rauniyar

Reputation: 85545

Just you need last() method

$('<div id="NextElement"' + id +'>' + /*Add after the last element*/ + '</div>')
.insertAfter($('[id^="NextElement"]').last());

Upvotes: 31

Related Questions