1

I want to order items inside a div,I have list fetched dynamically structured like this:

<div class="array-placeholder">
<div class="tag">....</div> #index 0 
<div class="tag">....</div> #index 1
<div class="tag">....</div> #index 2
</div>

I want to append an element

<div class="array-placeholder">
<div class="tag">....</div> #index 0 
<div class="tag">....</div> #index 1
<div class="tag">....</div> #index 2
<li><div class="tag">....</div></li> # index =0 but it should be 3
</div>

I tried to solve this like this but the index is always 0

newElem.insertAfter($(".array-placeholder").find('.tag').eq((listLength-1)));

Thanks for your help.

2
  • 1
    <li> inside <div class="array-placeholder"> is invalid HTML Commented Dec 27, 2019 at 11:13
  • Inside "eq()" method too much brackets. It should .eq(listLength-1)); Commented Dec 27, 2019 at 11:44

3 Answers 3

2

Rather than insertAfter, it would be simpler to use jQuery's append method:

$(".array_placeholder").append(newElem);

This will simply tack the new element onto the list as the last child.

Sign up to request clarification or add additional context in comments.

1 Comment

$(".array_placeholder") has other children that are dynamic that I didn't mention but it seems that I found the solution which is finding a way to delete the appended <li>
1

Have you tried with jQuery :last-child selector like following?

var newElem = '<li><div class="tag">....</div></li>';
$(newElem).insertAfter($(".array-placeholder .tag:last-child"));
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="array-placeholder">
<div class="tag">....</div>
<div class="tag">....</div>
<div class="tag">....</div>
<div class="tag">las tag</div>
</div>

Comments

1

this will definitely work while using jquery

var newElem = '<div class="tag">....</div>';
$(".array-placeholder").append(newElem);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.