Laravel Laravel - 11 months ago 146
CSS Question

jQuery insert after li element with attribute

I have list:

<ul class="customList">
<li data-featured="1">First item</li>
<li data-featured="0">Another item</li>
<li data-featured="0">Last item..</li>
</ul>


How can I insert my custom
<li>
after
featured="1"
? If all featured 0, then insert as first
li
.. Thanks in advance.

var self = this;
self.scope.find('.customList').prepend(myCustomItem); //this code inserts in begin, not after featured items..
$(myCustomItem).insertAfter('[data-featured="1"]'); //I've tried to build something.. but this fails


Sorry for my bad English

EDIT

newStatus.insertAfter('[data-featured="1"]');
looks like is working, but when there is any data-featured=1, then nothing happens. Any suggestions?

Answer Source

You can first use the jQuery attribute selector [attribute=value]: to check if li with data-featured="1" is exist or not. If exist then use the jQuery method .insertAfter() to insert the new li after it and if not then insert new li at the first position using .insertBefore().

if($('.customList li[data-featured="1"]').length>0)
{
      $("<li data-featured='99'>NEW ITEM</li>").insertAfter('.customList li[data-featured="1"]');
}
else
{
      $("<li data-featured='99'>NEW ITEM</li>").insertBefore('.customList li:first');
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul class="customList">
    <li data-featured="0">First item</li>
    <li data-featured="0">Another item</li>
    <li data-featured="0">Last item..</li>
</ul>

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download